我想知道是否有人可以告诉我这种行为在 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 中执行此操作,原因如下:
- 泛型协变仅适用于接口(interface)、数组和委托(delegate)类型,不适用于基类
- 您的 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
关于C# .NET 4.0 和泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2611926/