我有一個類和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()
方法得到這個錯誤:
Type of conditional expression cannot be determined because there is no implicit conversion between {namespace}.OrganizationRepresentative and {namespace}.Student.
我缺少什麼?
兩個類對彼此一無所知,但只有通用性是用戶基類。你應該對用戶進行一次強制轉換,因爲你不能創建和分配一個不同於潛在的其他具體對象的對象,因此你試圖實例化哪個對象。 –
http://stackoverflow.com/questions/828950/why-doesnt-this -c-sharp-code-compile – Habib