开发者

Casting Generics

开发者 https://www.devze.com 2023-03-14 13:39 出处:网络
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

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

精彩评论

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