且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

IList<T>并列出<T>接口转换

更新时间:2022-05-15 15:31:52

有一个合乎逻辑的解释,这个确切的问题几乎每天都在 *** 上被问到.

There is a logical explanation, and this exact question is asked pretty much every day on ***.

假设这是合法的:

IList<IAnimal> cats = new List<Cat>(); 

是什么阻止了这合法化?

What stops this from being legal?

cats.Add(new Giraffe());

什么都没有."cats" 是动物列表,而长颈鹿是动物,因此您可以将长颈鹿添加到猫列表中.

Nothing. "cats" is a list of animals, and a giraffe is an animal, and therefore you can add a giraffe to a list of cats.

显然这不是类型安全的.

Clearly that is not typesafe.

在 C# 4 中,我们添加了一项功能,如果元数据注释允许编译器证明它是类型安全的,您就可以这样做.在 C# 4 中,您可以这样做:

In C# 4 we added a feature whereby you can do that if the metadata annotations allow the compiler to prove that it is typesafe. In C# 4 you can do this:

IEnumerable<IAnimal> cats = new List<Cat>(); 

因为 IEnumerable<IAnimal> 没有 Add 方法,所以没有办法违反类型安全.

because IEnumerable<IAnimal> has no Add method, so there is no way to violate type safety.

有关更多详细信息,请参阅我关于我们如何在 C# 4 中设计此功能的系列文章.

See my series of articles on how we designed this feature in C# 4 for more details.

http://blogs.msdn.com/b/ericlippert/archive/tags/covariance+and+contravariance/default.aspx

(从底部开始.)