gpt4 book ai didi

c# - 是什么导致此 'No Implicit Conversion' 错误?

转载 作者:行者123 更新时间:2023-12-02 01:03:58 24 4
gpt4 key购买 nike

我有一个类和两个子类:

public class User
{
public string eRaiderUsername { get; set; }
public int AllowedSpaces { get; set; }
public ContactInformation ContactInformation { get; set; }
public Ethnicity Ethnicity { get; set; }
public Classification Classification { get; set; }
public Living Living { get; set; }
}

public class Student : User
{
public Student()
{
AllowedSpaces = AppSettings.AllowedStudentSpaces;
}
}

public class OrganizationRepresentative : User
{
public Organization Organization { get; set; }

public OrganizationRepresentative()
{
AllowedSpaces = AppSettings.AllowedOrganizationSpaces;
}
}

我已经创建了一个数据模型来捕获表单数据并为用户返回正确的对象类型:

public class UserData
{
public string eRaiderUsername { get; set; }
public int Ethnicity { get; set; }
public int Classification { get; set; }
public int Living { get; set; }
public string ContactFirstName { get; set; }
public string ContactLastname { get; set; }
public string ContactEmailAddress { get; set; }
public string ContactCellPhone { get; set; }
public bool IsRepresentingOrganization { get; set; }
public string OrganizationName { get; set; }

public User GetUser()
{
var user = (IsRepresentingOrganization) ? new OrganizationRepresentative() : new Student();
}
}

但是,我在 GetUser() 方法中的三元操作失败并出现此错误:

Type of conditional expression cannot be determined because there is no implicit conversion between {namespace}.OrganizationRepresentative and {namespace}.Student.

我错过了什么?

最佳答案

您必须将三元表达式的第一个分支显式转换为基本类型 (User),以便编译器可以确定表达式可以求值的类型。

var user = (IsRepresentingOrganization) 
? (User)new OrganizationRepresentative()
: new Student();

编译器不会自动推断表达式应使用哪种基类型,因此您必须手动指定。

关于c# - 是什么导致此 'No Implicit Conversion' 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24810582/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com