2014-07-17 61 views
0

我有一個類和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.

我缺少什麼?

+0

兩個類對彼此一無所知,但只有通用性是用戶基類。你應該對用戶進行一次強制轉換,因爲你不能創建和分配一個不同於潛在的其他具體對象的對象,因此你試圖實例化哪個對象。 –

+0

http://stackoverflow.com/questions/828950/why-doesnt-this -c-sharp-code-compile – Habib

回答

6

您必須明確地將三元表達式的第一個分支轉換爲基本類型(User),以便編譯器可以確定表達式可以計算的類型。

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

編譯器不會自動推斷出該表達式應使用哪種基本類型,因此您必須手動指定它。

+0

+1,這肯定是原因,而不是'var' – Habib

+2

出於好奇,爲什麼你不需要將'new Student()'也轉換爲'User'呢? – Alex

+0

@Alex,一旦您指定了第一個分支('User')的類型,那麼只有條件運算符的操作數中的一個可以轉換爲基類 – Habib

相關問題