作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个类和两个子类:
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/
我是一名优秀的程序员,十分优秀!