我能投射吗
IInterface<MyClass>
为了
IInterface<IAnother>
当MyClass实现IAnother接口时,会发生什么?
在 C# 4 via Covariance 中是可能的,只要你正确地装饰你的使用场景(即:IInterface<out IAnother>
)。
请注意,这样做可能会产生潜在的副作用,具体取决于您的接口使用情况。我建议阅读Variance in Generic Interfaces以获取更多详细信息,但主要问题是可能会出现运行时错误,因为您正在放弃一些类型安全性。
了解C# 4.0中的协变和逆变
(IInterface<IAnother>)myInstanceOfIInterfaceWithMyClass;
- Patrick Perini