我有一个类和2个子类:
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()
方法中的三元操作失败并出现此错误:
无法确定条件表达式的类型,因为{namespace} .OrganizationRepresentative和{namespace} .Student之间没有隐式转换。
我错过了什么?
答案 0 :(得分:6)
您必须显式地将三元表达式的第一个分支强制转换为基类型(User
),以便编译器可以确定表达式可以评估的类型。
var user = (IsRepresentingOrganization)
? (User)new OrganizationRepresentative()
: new Student();
编译器不会自动推断出应该为表达式使用哪种基类型,因此您必须手动指定它。