public void Foo (IEnumerable<object> objects)
{
}
var strings = new List<string>{"first", "second", "third"};
Foo(strings); // Compilation Error.
Foo(strings.Cast<object>()); // O.k.
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).
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.