gpt4 book ai didi

C# .NET 4.0 和泛型

转载 作者:行者123 更新时间:2023-11-30 15:48:26 25 4
gpt4 key购买 nike

我想知道是否有人可以告诉我这种行为在 C# 4.0 中是否可行

我有一个对象层次结构,我想保持强类型。像这样

class ItemBase {}

class ItemType<T> where T : ItemBase
{
T Base { get; set; }
}


class EquipmentBase : ItemBase {}
class EquipmentType : ItemType<EquipmentBase> {}

我想做些什么才能拥有这样的东西

ItemType item = new EquipmentType();

我希望 item.Base 返回类型 ItemBase。基本上我想知道它是否足够聪明,可以在没有强类型的情况下强类型泛型到基类。这样做的好处是我可以简单地将 ItemType 转换回 EquipmentType 并再次获得所有强类型。

我可能是想错了......

最佳答案

你在谈论允许你做的协方差:

ItemType<object> item = new EquipmentType();

您不能在 C# 4 中执行此操作,原因如下:

  1. 泛型协变仅适用于接口(interface)、数组和委托(delegate)类型,不适用于基类
  2. 您的 ItemType 类使用 T 作为输入/输出类型参数,这意味着它接收 T 并返回 T。

第二个是主要问题,因为如果允许,则以下代码必须是可编译的,但在运行时会失败。

// this will not work
ItemType<object> item = new EquipmentType();
item.Base = new Object(); // this seems ok but clearly isn't allowed

Covariance and Contravariance FAQ

关于C# .NET 4.0 和泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2611926/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com