Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ruby-on-rails-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 这是什么原因造成的';无隐式转换';错误?_C# - Fatal编程技术网

C# 这是什么原因造成的';无隐式转换';错误?

C# 这是什么原因造成的';无隐式转换';错误?,c#,C#,我有一个类和两个子类: public class User { public string eRaiderUsername { get; set; } public int AllowedSpaces { get; set; } public ContactInformation ContactInformation { get; set; } public Ethnicity Ethnicity { get; set; } public Classifi

我有一个类和两个子类:

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之间没有隐式转换


我缺少什么?

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

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

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

这两个类彼此都不了解,但只有通用性是用户基类。您应该对您试图实例化的任何对象执行强制转换,因为出于好奇,您无法创建不同的对象并将其分配给可能的其他具体对象。为什么不将
new Student()
也强制转换为
User
,只有一个条件运算符的操作数可以转换为基类,@Alex一旦指定了第一个分支(
User
)的类型,编译器就可以找到第二个分支(
Student
)类型的隐式转换,因为这是一个简单的加宽转换,三元if只能返回一个类型(或者这些类型必须是隐式可转换的)。也就是说,您不能执行类似(a==true?“X”:5)的操作—您需要将其更改为(a==true?“X”:“5”)。看见