简体   繁体   中英

Strongly typed collection Implicit and explicit cast

public void Foo (IEnumerable<object> objects)
{
}

var strings = new List<string>{"first", "second", "third"};
Foo(strings); // Compilation Error.
Foo(strings.Cast<object>()); // O.k.
  1. Why the first call to Foo doesn't compile? string derived from object.
  2. If I can cast the list to object and it's compiled, why the compiler doesn't do it by his own?

The first call compiles in .NET 4.0.

In previous versions, the generic types have to match exactly .

I suggest reading the blogs posts of Eric Lippert regarding variance (covariance and contravariance).

  1. Generics are strict in the sense that you cannot assign a collection of a derived type to a collection of a supertype. You must provide the exact type used to instantiate the collection.
  2. Because it cannot know what you want to do. Same reason why the following line does not compile:

     string s = new object(); 

To force an "unsafe" type cast on the user would be too much liberty given to the compiler.

You wan't to look up co-variance and contra-variance .

It's new feature in .NET 4.0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM