[英]What is causing this 'No Implicit Conversion' error?
我有一個類和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之間沒有隱式轉換。
我想念什么?
您必須將三元表達式的第一個分支顯式轉換為基本類型( User
),以便編譯器可以確定表達式可以求值的類型。
var user = (IsRepresentingOrganization)
? (User)new OrganizationRepresentative()
: new Student();
編譯器不會自動推斷該表達式應使用哪種基本類型,因此您必須手動指定它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.