儘管在Google和SO上搜索,但似乎無法知道如何在.NET2.0
中執行此操作。如何在.NET 2中顯式轉換此派生類?
說我有以下類:
public class Fruit {
prop string Color {get; set;}
}
public class Apple : Fruit {
public Apple() {
this.Color = "Red";
}
}
public class Grape: Fruit {
public Grape() {
this.Color = "Green";
}
}
現在,我想這樣做:
public List<Fruit> GetFruit() {
List<Fruit> list = new List<Fruit>();
// .. populate list ..
return list;
}
List<Grape> grapes = GetFruit();
但是,當然,我得到Cannot implicitly convert type Fruit to Grape
。
我知道這是因爲我真的可以把事情搞得一團糟,如果我做的:
List<Grape> list = new List<Grape>();
list.add(new Apple());
因爲雖然兩者都是Fruit
,一個Apple
不是Grape
。所以這是有道理的。
但我不明白爲什麼我不能做到這一點:
最起碼,我需要能夠:
List<Fruit> list = new List<Fruit>();
list.add(new Apple()); // will always be Apple
list.add(new Apple()); // will always be Apple
list.add(new Apple()); // will always be Apple
如何做任何想法這在.NET2
?
感謝
編輯
對不起,我錯了。我其實可以這樣做:
的.FindAll
和.Convert
的伎倆。
'prop string Color {get;設置;}'道具? – asawyer
「但我不明白爲什麼我不能做到這一點」 - 到目前爲止我所知,你應該能夠做到這一點(假設你糾正Add'的'的情況下,使'Fruit'編譯) –
「但我不明白爲什麼我不能做到這一點:」 - 你可以,只要你用'add',而不是'add'(不存在);最後的所有例子都很好。 –