C# .NET 4.0 generic covariance problem with cast exception
I have been battling with this for a while, so any help would be appreciated. Here's the scenario i am faced with on C# .NET 4.0.
public interface ITableBusinessLogicLayerIn<in TTableRecord> : IBusinessLogicLayer
where TTableRecord : ITableRecord
{
// No definition
}
public interface ITableBusinessLogicLayerOut<out TTableRecord> : IBusinessLogicLayer
where TTableRecord : ITableRecord
{
// No definition
}
I 开发者_运维问答have an object which implements both interfaces. Code compiles fine. But at runtime, I am able to cast this object as follows:
(ITableBusinessLogicLayerOut<ITableRecord>)obj
but not as this:
(ITableBusinessLogicLayerIn<ITableRecord>)obj
This is highly confusing, i'm not sure what i am doing wrong. Someone please point me in the right direction. Thanks!
Contravariance (in) allows you to cast an object with a type parameter of a less-specific type to one of a more-specific type. For example, you can't pass an object to a type the expects a string, so you can't cast a type that expects a string to a type that expects an object. See here for more information: http://msdn.microsoft.com/en-us/library/ee207183%28d=lightweight%29.aspx
Given the following example:
class MyTableRecord : ITableRecord { }
ITableBusinessLogicLayerIn<ITableRecord> inA;
ITableBusinessLogicLayerIn<MyTableRecord> inB;
ITableBusinessLogicLayerOut<ITableRecord> outA;
ITableBusinessLogicLayerOut<MyTableRecord> outB;
You can assign inB
to inA
, but not the reverse. You can assign outA
to outB
, but not the reverse.
精彩评论