【发布时间】:2015-04-26 06:54:42
【问题描述】:
在下面的示例中,我可以添加 List 类型为 Animal。由于Dog 和Cat 派生自动物,因此List 可以分别保存。但是,如果我有一个接受List<Animal> 的方法,则不能传入引用List<Dog>。如果Dog 来源于动物,为什么这无效?但是,如果我有一个方法可以排除 Object 类型的参数,并且所有对象都派生自 Object,那么它可以工作。
class Program
{
static void Main(string[] args)
{
List<Animal> animals = new List<Animal>();
animals.Add(new Dog() { Color = "Black" }); // allowed since Dog derives from Animal
List<Dog> dogs = new List<Dog>();
dogs.Add(new Dog() { Color = "White" });
Test(animals);
Test(dogs); // not allowed - does not compile
Test2(dogs); // valid as all objects derive from object
}
static void Test(List<Animal> animals) {
// do something
}
static void Test2(object obj) {
}
}
public class Animal {
public String Color { get; set; }
}
public class Dog : Animal { }
public class Cat : Animal { }
【问题讨论】:
-
试试
static void Test(IEnumerable<Animal> animals) -
搜索
covariance and contravariance in c# -
正如 Selman22 建议的那样,看看here
-
@MatthewWatson - 听起来像是答案。为什么不让它成为一个答案?
-
@PhilVallone 已添加到我现有的答案中。
标签: c#