加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C#泛型继承

发布时间:2020-12-16 01:38:58 所属栏目:百科 来源:网络整理
导读:我有以下课程 public class AccountingBaseTItemType where TItemType : AccountingItemBase 在我的AccountingItemBase中,我有以下属性: public virtual AccountingBaseAccountingItemBase Parent { get; set; } 在我的AccountingBase中,我正在尝试执行以下
我有以下课程

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具有通用性……但这最终会导致递归问题,实际上……

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读