开发者

A Solution For (IEnumerable<Base>)Derive; Yet? [duplicate]

开发者 https://www.devze.com 2023-01-01 05:43 出处:网络
This question already has answers here: Closed 12 years ago. Possible Duplicate: C# Cannot c开发者_如何学Convert from IEnumerable<Base> to IEnumerable<Derived>
This question already has answers here: Closed 12 years ago.

Possible Duplicate:

C# Cannot c开发者_如何学Convert from IEnumerable<Base> to IEnumerable<Derived>

I have D1 and D2 which derive from B. When i write var ls = (IEnumerable<B>)(cond?lsD1:lsD2); I get a runtime cast error. IIRC this is a well known problem. My question is

1) Is this allowed yet? perhaps in .NET 4? I have 2010 but my project is a few months old, large and targets 3.5.

2) Is there a simple workaround? I only need to read the list not add anything or remove. Actually, ToArray() would probably work but is there another solution?


So if I'm reading your question correctly, this is an example of covarience. C# 4 supports this for some interfaces IEnumerable being one of them.

The workaround in C# 3 would probably be something along the lines of:

var ls = (IEnumerable<B>)(cond ? lsD1.Cast<B>() : lsD2.Cast<B>());

Turning them into arrays would also work, but only because variance is "broken" (see section: Broken array variance) for arrays.


I believe your best bet is to use the Cast<T> extension on the lists. Something like

var ls = cond ? lsD1.Cast<B>() : lsD2.Cast<B>();
0

精彩评论

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

关注公众号