C# .NET 4.0 带有强制转换异常的泛型协方差问题
我已经为此奋斗了一段时间,所以任何帮助将不胜感激。这是我在 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
}
我有一个实现这两个接口的对象。代码编译良好。但在运行时,我可以按如下方式强制转换该对象:
(ITableBusinessLogicLayerOut<ITableRecord>)obj
但不是这样:
(ITableBusinessLogicLayerIn<ITableRecord>)obj
这是非常令人困惑的,我不确定我做错了什么。请有人指出我正确的方向。谢谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
逆变 (in) 允许您将具有不太特定类型的类型参数的对象转换为更特定类型之一。例如,您无法将对象传递给需要字符串的类型,因此您无法将需要字符串的类型转换为需要对象的类型。有关详细信息,请参阅此处:http://msdn.microsoft .com/en-us/library/ee207183%28d=lightweight%29.aspx
给出以下示例:
您可以将
inB
分配给inA
,但不能反之亦然。您可以将outA
分配给outB
,但反之则不行。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:
You can assign
inB
toinA
, but not the reverse. You can assignoutA
tooutB
, but not the reverse.