C#泛型继承 [英] C# Generics Inheritance
问题描述
我有下面的类
public class AccountingBase<TItemType> where TItemType : AccountingItemBase
在我AccountingItemBase我有以下属性:
And in my AccountingItemBase i have the following property:
public virtual AccountingBase<AccountingItemBase> Parent { get; set; }
在我AccountingBase,我尝试做以下
in my AccountingBase, I am trying to do the following
item.Parent = this;
按道理这应该工作,因为TItemType从AccountingItemBase继承,而是我得到以下错误:
Logically this should work, as TItemType inherits from AccountingItemBase, but instead i get the following error:
> Error 1 Cannot implicitly convert type
> 'TGS.MySQL.DataBaseObjects.AccountingBase<TItemType>'
> to
> 'TGS.MySQL.DataBaseObjects.AccountingBase<TGS.MySQL.DataBaseObjects.AccountingItemBase>'
我可以如何设置子属性parent属性本身(父类中)
How can i set the child properties parent property to itself (inside the parent class)
推荐答案
没有,你的直觉是不正确。它不应该工作,因为通用类不是在.NET变体。
No, your intuition is incorrect. It shouldn't work, because generic classes aren't variant in .NET.
仅仅因为 TItemType
继承自 AccountingItemBase
并不意味着 AccountingBase< TItemType> AccountingItemBase>
从 AccountingBase<继承code>。假设
AccountingBase< TItemType>
有类型的字段 TItemType
。那么,如果你的直觉是正确的,你可以写:
Just because TItemType
inherits from AccountingItemBase
doesn't mean that AccountingBase<TItemType>
inherits from AccountingBase<AccountingItemBase>
. Suppose AccountingBase<TItemType>
had a field of type TItemType
. Then if your intuition were correct, you could write:
AccountingBase<SomeSubtype> x = new AccountingBase<SomeSubtype>();
AccountingBase<AccountingItemBase> y = x;
y.SomeField = new OtherSubtype();
这显然打破类型安全,因为当在看作为一个 AccountingBase< SomeSubtype>
,该领域,就是要键入 SomeSubtype
,但你已经把键入 OtherSubtype <值/ code>在那里!
That would clearly break type safety, because when looked at as an AccountingBase<SomeSubtype>
, the field is meant to be of type SomeSubtype
, but you've put a value of type OtherSubtype
in there!
基本上,普通的方差是一个复杂的话题。
Basically, generic variance is a complex topic.
我建议你读埃里克利珀的漫长而细致的博客文章系列了解详情。或者我从 NDC 2010 这可能对你有用。基本上在.NET 4中还有的部分的通用方差,但它是有限的。
I suggest you read Eric Lippert's long and detailed blog post series for more information. Or I have a video from NDC 2010 which you may find useful. Basically in .NET 4 there's some generic variance, but it's limited.
现在,因为你可以在你的情况做的:
Now, as to what you can do in your situation:
- 您可以创建一个的非泛型的基类,它
AccountingBase
继承从。这可能是最好的主意。然后让父类型
属性,该属性的非泛型类型。 - 您可以让
AccountingBase
在本身和其母公司通用...但是,这最终导致递归问题,有效的...
- You could create a nongeneric base class which
AccountingBase
inherits from. That's probably the best idea. Then make the type of theParent
property that nongeneric type. - You could make
AccountingBase
generic in both itself and its parent... but that ends up causing recursion issues, effectively...
这篇关于C#泛型继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!