开发者

Casting Generics

Can I cast

IInterface<MyClass>

to

IInterface<IAnother>

when MyClass implements IAnothe开发者_开发问答r?


Yes, but only if your're using C# 4 (or beyond) and, IInterface is declared as IInterface<out T>.

This is called generic covariance, you can find more information on MSDN, or this (more formal but more understandable) introduction from Bart de Smet.


This is possible in C# 4 via Covariance, provided you decorate your usage scenario correctly (ie: IInterface<out IAnother>).

Note that there are potential side effects to doing this, depending on your interface usage. I recommend reading up on Variance in Generic Interfaces for more details, but the main issue is that it's possible to get yourself into a situation where you can have runtime errors because you're giving up some type safety.


look at covariance and contravariance in C# 4.0

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜