[英]C# .NET 4.0 and Generics
我想知道是否有人可以告诉我在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中执行此操作:
数字2是主要问题,因为如果允许,则必须编译以下代码,但在运行时失败。
// this will not work
ItemType<object> item = new EquipmentType();
item.Base = new Object(); // this seems ok but clearly isn't allowed
没有,因为ItemType
只要编译器而言是从一个单独的类型ItemType<EquipmentBase>
或ItemType<Foo>
。 这三种都被视为独特的类型,它们不能代表彼此。
在类声明中,您将其声明为ItemType<T>
,因此ItemType
将是未编译的未定义类型。
最好的情况是,您可以使用ItemType<EquipmentBase>
对象来表示EquipmentType
或从ItemType<EquipmentBase>
派生但不是ItemType<PersonType>
任何其他类。
我不认为C#4.0的新功能会帮助你。 但是,有一种方法可以解决这个问题,因为引入了泛型:你创建一个与泛型类同名的抽象基类,并放置你想要的所有成员,不需要接受或返回参数泛型类型,如下:
class ItemBase {
}
abstract class ItemType {
public ItemBase Base {
get { return GetItemBase(); }
set { SetItemBase(value); }
}
protected abstract void SetItemBase(ItemBase value);
protected abstract ItemBase GetItemBase();
}
class ItemType<T> : ItemType where T : ItemBase {
protected override sealed void SetItemBase(ItemBase value) {
Base = (T) value;
}
protected override sealed ItemBase GetItemBase() {
return Base;
}
public new T Base { get; set; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.