我有以下类(class)
public class AccountingBase<TItemType> where TItemType : AccountingItemBase
在我的 AccountingItemBase 中我有以下属性:
public virtual AccountingBase<AccountingItemBase> Parent { get; set; }
在我的 AccountingBase 中,我正在尝试执行以下操作
item.Parent = this;
逻辑上这应该有效,因为 TItemType 继承自 AccountingItemBase,但我却收到以下错误:
> Error 1 Cannot implicitly convert type
> 'TGS.MySQL.DataBaseObjects.AccountingBase<TItemType>'
> to
> 'TGS.MySQL.DataBaseObjects.AccountingBase<TGS.MySQL.DataBaseObjects.AccountingItemBase>'
如何将子属性的父属性设置为其自身(在父类中)
最佳答案
不,你的直觉是错误的。它不应该起作用,因为泛型类在 .NET 中没有变体。
仅仅因为TItemType
继承自 AccountingItemBase
并不意味着 AccountingBase<TItemType>
继承自 AccountingBase<AccountingItemBase>
.假设 AccountingBase<TItemType>
有一个类型为 TItemType
的字段.然后如果你的直觉是正确的,你可以写:
AccountingBase<SomeSubtype> x = new AccountingBase<SomeSubtype>();
AccountingBase<AccountingItemBase> y = x;
y.SomeField = new OtherSubtype();
这显然会破坏类型安全,因为当被视为 AccountingBase<SomeSubtype>
时, 该字段的类型应为 SomeSubtype
, 但你输入了 OtherSubtype
类型的值在那里!
基本上,泛型方差是一个复杂的话题。
我建议您阅读 Eric Lippert 的长而详细的 blog post series想要查询更多的信息。或者我有来自 NDC 2010 的视频你可能会觉得有用。基本上在 .NET 4 中有一些通用变体,但它是有限的。
现在,关于在您的情况下您可以做什么:
- 您可以创建一个非泛型 基类
AccountingBase
继承自。这可能是最好的主意。然后制作Parent
的类型非泛型类型的属性。 - 你可以制作
AccountingBase
在其自身及其父级中都是通用的……但这最终会有效地导致递归问题……
关于C#泛型继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4043702/