开发者

type casting not working in 3.5 as in 4.0

开发者 https://www.devze.com 2023-02-17 17:10 出处:网络
public class Entity 开发者_运维问答{ public int Id {get;set;} } public class Foo : Entity { public string Name {get;set;}
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>
0

精彩评论

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

关注公众号