【发布时间】:2012-10-18 21:47:34
【问题描述】:
尽管搜索了 Google 和 SO,但我似乎无法在 .NET2.0 中找到如何执行此操作。
假设我有以下课程:
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());
list.add(new 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 中执行此操作的任何想法?
谢谢
编辑
对不起,我弄错了。事实上我可以做到:
List<Fruit> list = new List<Fruit>();
list.add(new Apple());
list.add(new Grape());
.FindAll 和 .Convert 成功了。
【问题讨论】:
-
prop string Color {get; set;}道具? -
“但我不明白为什么我不能这样做” - 据我所知,你应该能够做到这一点(假设你更正了
Add和使Fruit可编译) -
“但我不明白为什么我不能这样做:” - 你可以,只要你使用
Add而不是add(不存在);最后的所有例子都很好。 -
@Damien_The_Unbeliever 是对的...我已经在 .NET 2.0 上进行了尝试,以确保 100% 可以正常工作
-
@asawyer 是的。我输入了“prop”,因为这是 Visual Studio 上的快捷方式。哈哈。我已经习惯了打字,以至于它不假思索地就出来了。大声笑和马克和保罗。你说的都是对的。我可以做到这一点。那是我的一个错误。
标签: .net generics inheritance .net-2.0 derived-class