开发者

Why covariant type parameters don't allow me to write [List<object> lst = new List<string>()]?

If the Covariant type parameters which added in .Net Framework 4 enable me to make assignments that look like polymorphism

Why I c开发者_如何转开发an write

IEnumerable<object> lst = new List<string>();

And I can't write

List<object> lst = new List<string>();


There are 2 reasons why it doesn't work:

  • IEnumerable<T> is covariant (it is declared public interface IEnumerable<out T>), but IList<T> isn't. Otherwise you would be able to do something like that:

    IList<string> listOfStrings = ...
    IList<object> listOfObjects = listOfStrings;
    listOfObjects.Add(42); // would fail at runtime because it is actually a list of strings, not ints
    
  • Covariance and contravariance only work on interfaces, not on concrete classes

From MSDN:

In the .NET Framework version 4, variant type parameters are restricted to generic interface and generic delegate types.


Because the List{T} type is invariant, thus in the second case it would be possible to do:

List<object> lst = new List<string>();
lst.Add(10);

This is invalid because you are adding an Int32 to a list of strings.

The IEnumerable{out T} type is covariant as implied by the 'out'. This means it is not possible to add items to it, only get items out of it, which makes the first statement valid.

This however is valid:

List<object> lst = new List<object>();
lst.AddRange(new string[] { "hello" });
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜