繁体   English   中英

C# 如何从抽象泛型 class 继承 class 并使用泛型 class 作为类型参数

[英]C# How to inherit class from abstract generic class with generic class as type parameter

我有以下抽象类:

public abstract class Entry;
public abstract class Table<TEntry> where TEntry : Entry;
public abstract class Parser<TTable> where TTable : Table<Entry>;

Entry是包含数据字典的表条目的基本 class。

Table是包含条目的 IEnumerables 以及其他一些信息的表的基本 class。

Parser是文本解析器的基础 class,它可以读取字符串并将它们转换为条目的 ICollection 条目,并且可以将它们的 ICollection 转换为表。

public class MyEntry : Entry;
public class MyTable : Table<MyEntry>;
public class MyParser : Parser<MyTable>;

在尝试像这样实现这些基类的子类时,我收到错误 CS0311: The type 'MyTable' cannot be used as type parameter 'TTable' in the generic type or method 'Parser<TTable>'. There is no implicit reference conversion from 'MyTable' to 'Table<Entry>' The type 'MyTable' cannot be used as type parameter 'TTable' in the generic type or method 'Parser<TTable>'. There is no implicit reference conversion from 'MyTable' to 'Table<Entry>'

但是, out只能在通用类型的接口上指定。 我需要在这里使用抽象的 class ,因为我想要保护一些基本的 class 行为,而不是公开。

我怎样才能解决这个问题?

正如 msdn 所说,它看起来不符合 class 的条件:

  • 变体类型参数仅限于泛型接口和泛型委托类型

因此 class 的变体类型参数不是协变的。 “协变”表示派生的 class 的分配与基本类型兼容:

public class Fruit
{ 
}

public class Apple : Fruit
{ }

这段代码完全符合条件:

IEnumerable<Fruit> fruits = new List<Apple>();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM