public class Entity
开发者_运维问答{
public int Id {get;set;}
}
public class Foo : Entity
{
public string Name {get;set;}
}
//foos is an IEnumerable<Foo> with List<Foo> value
foos as IEnumerable<Entity> //works in .net 4.0, doesn't work in 3.5,
how to get a similar behaviour in 3.5
This construct relies on covariance/contravariance which was introduced in .net 4.0. You will not be able to get this to work on earlier versions.
Here's a nice article about it: http://blogs.msdn.com/b/csharpfaq/archive/2010/02/16/covariance-and-contravariance-faq.aspx
As JoDG points out, this is enabled by the new co-variance feature in c#4 - the closest you can get in c#3 is:
IEnumerable<Entity> entities = foos.Cast<Entity>();
without Co/Contravariance you have to cast yourself:
var entities = foos.Cast<Entity>(); // yields IEnumerable<Entity>
精彩评论