2017-06-19 54 views
0

我有一個接口有效,稱爲IUser變量是一個類型,它是不是在給定的情況下

我有兩個型號,UserGuest二者均實現IUser

我有一個類,所謂CardOut什麼有兩個屬性,CardUser

這裏是CardOut類的構造函數:

public CardOut(Interfaces.IUser User, Card Card) { 
    this.User = User; 
    this.Card = Card; 
} 

我正在從數據庫中取出一些行,並根據單元格的類型創建UserGuest

foreach (IDictionary<string, string> row in rows) { 
    if (row["type"] == "xxx") { 
     User UserValue = new User(); 
     UserValue.buildById(int.Parse(row["user_id"])); 
    } else { 
     Guest UserValue = new Guest(); 
     UserValue.buildById(int.Parse(row["id"])); 
    } 
    Card Card = new Card(); 
    Card.buildCardByIndex(int.Parse(row["cardindex"])); 
    CardOut CardOut = new CardOut(UserValue, Card); //Here is the error 
} 

當我想要實例化一個新的CardOut對象我收到此錯誤:

Error CS0103 The name 'UserValue' does not exist in the current context

我該如何解決呢?我不能在if條件之外創建它,因爲我不知道應該實例化哪個類。

回答

5

if塊之外聲明類型IUser的變量,並在具體類型的if內實例化它。

編輯:添加了一個演員自IUser似乎沒有成員buildById

foreach (IDictionary<string, string> row in rows) { 
    IUser UserValue; 
    if (row["type"] == "xxx") { 
     UserValue = new User(); 
     ((User)UserValue).buildById(int.Parse(row["user_id"])); 
    } else { 
     UserValue = new Guest(); 
     ((Guest)UserValue).buildById(int.Parse(row["id"])); 
    } 
    Card Card = new Card(); 
    Card.buildCardByIndex(int.Parse(row["cardindex"])); 
    CardOut CardOut = new CardOut(UserValue, Card); 
} 
+0

的問題是:'錯誤CS1061 \t「IUSER」不包含「buildById''的定義。爲什麼「IUser」有這種方法顯而易見?如果'User'擁有和'Guest'以其他方式構建? – vaso123

+0

@ vaso123然後你必須將其轉換回來,或創建一個具體類型的臨時變量,然後將其分配給'IUser'變量。看我的編輯。但是如果你可以改變接口的實現,我會在那裏添加方法。 – Adrian

+0

好的,這就是我剛纔提到的情況。我正在從兩個數據庫工作。 'User.buildById()'使用DB1,而'Guest.buildById()'使用DB2。現在我需要編寫一個新的方法'User.buildByDB2Id()',這個方法不會在'Guest'類中。我有訪問接口。 – vaso123

相關問題