C# .NET 4.0 带有强制转换异常的泛型协方差问题

发布于 2024-10-31 03:33:20 字数 651 浏览 3 评论 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

执手闯天涯 2024-11-07 03:33:20

逆变 (in) 允许您将具有不太特定类型的类型参数的对象转换为更特定类型之一。例如,您无法将对象传递给需要字符串的类型,因此您无法将需要字符串的类型转换为需要对象的类型。有关详细信息,请参阅此处:http://msdn.microsoft .com/en-us/library/ee207183%28d=lightweight%29.aspx

给出以下示例:

class MyTableRecord : ITableRecord { }
ITableBusinessLogicLayerIn<ITableRecord> inA;
ITableBusinessLogicLayerIn<MyTableRecord> inB;
ITableBusinessLogicLayerOut<ITableRecord> outA;
ITableBusinessLogicLayerOut<MyTableRecord> outB;

您可以将 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:

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文