0
我有一個接口有效,稱爲IUser
變量是一個類型,它是不是在給定的情況下
我有兩個型號,User
和Guest
二者均實現IUser
我有一個類,所謂CardOut
什麼有兩個屬性,Card
和User
這裏是CardOut
類的構造函數:
public CardOut(Interfaces.IUser User, Card Card) {
this.User = User;
this.Card = Card;
}
我正在從數據庫中取出一些行,並根據單元格的類型創建User
或Guest
。
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條件之外創建它,因爲我不知道應該實例化哪個類。
的問題是:'錯誤CS1061 \t「IUSER」不包含「buildById''的定義。爲什麼「IUser」有這種方法顯而易見?如果'User'擁有和'Guest'以其他方式構建? – vaso123
@ vaso123然後你必須將其轉換回來,或創建一個具體類型的臨時變量,然後將其分配給'IUser'變量。看我的編輯。但是如果你可以改變接口的實現,我會在那裏添加方法。 – Adrian
好的,這就是我剛纔提到的情況。我正在從兩個數據庫工作。 'User.buildById()'使用DB1,而'Guest.buildById()'使用DB2。現在我需要編寫一個新的方法'User.buildByDB2Id()',這個方法不會在'Guest'類中。我有訪問接口。 – vaso123