导致此"无隐式转换"错误的原因是什么?

dre*_*att 0 c#

我有一个类和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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

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

无法确定条件表达式的类型,因为{namespace} .OrganizationRepresentative和{namespace} .Student之间没有隐式转换.

我错过了什么?

Ada*_*ras 6

您必须显式地将三元表达式的第一个分支强制转换为基类型(User),以便编译器可以确定表达式可以计算的类型.

var user = (IsRepresentingOrganization) 
               ? (User)new OrganizationRepresentative()
               : new Student();
Run Code Online (Sandbox Code Playgroud)

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

  • @Alex一旦指定了第一个分支(`User`)的类型,编译器就可以从第二个分支(`Student`)的类型中找到隐式转换,因为它是一个简单的加宽转换. (3认同)
  • 出于好奇,为什么你不需要将`new Student()`转换为'User`? (2认同)