C#泛型继承

标签 c# generics inheritance polymorphism

我有以下类(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/

相关文章:

Java 泛型 : Declare map value of generic type

java - 如何从删除中转换通用类型

c# - 如何使用包含空格的枚举项目名称?

c# - AutoMapper,在自定义类型转换器中调用 Mapper.Map() ?

java - 警告 : A generic array of Object&Serializable&Comparable<? > 是为可变参数创建的

scala - 只允许在同一个包内继承

c++ - 专门的纯虚拟模板函数的另一个问题(未定义的引用)

java - 我的 Java 中的 ShapeApp 出现问题

c# - .NET:如何判断编码是否支持我的字符串中的所有字符?

c# - 使用 DataStax c# 驱动程序的 Cassandra 批量插入