简体   繁体   English

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

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

I have the following abstract classes:我有以下抽象类:

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

Entry is a base class for a table entry containing a Dictionary of data. Entry是包含数据字典的表条目的基本 class。

Table is a base class for a table containing IEnumerables of Entries plus some other info. Table是包含条目的 IEnumerables 以及其他一些信息的表的基本 class。

Parser is a base class for text parsers which can read in strings and turn them into Entries for their ICollection of Entries, and can convert their ICollection to a Table. Parser是文本解析器的基础 class,它可以读取字符串并将它们转换为条目的 ICollection 条目,并且可以将它们的 ICollection 转换为表。

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

Upon trying to implement children of these base classes like so, I get the error 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>'在尝试像这样实现这些基类的子类时,我收到错误 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>' . 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>'

However, out can only be specified on generic types of interfaces.但是, out只能在通用类型的接口上指定。 I need to use an abstract class here since there is some base class behavior that I want to be protected, not public.我需要在这里使用抽象的 class ,因为我想要保护一些基本的 class 行为,而不是公开。

How can I fix this?我怎样才能解决这个问题?

It looks like it is not eligible for class as msdn says : 正如 msdn 所说,它看起来不符合 class 的条件:

  • Variant type parameters are restricted to generic interface and generic delegate types变体类型参数仅限于泛型接口和泛型委托类型

So variant type parameters for class are not covariant.因此 class 的变体类型参数不是协变的。 "Covariant" means that assignment of derived class copmatible with base type: “协变”表示派生的 class 的分配与基本类型兼容:

public class Fruit
{ 
}

public class Apple : Fruit
{ }

And this code is perfectly eligible:这段代码完全符合条件:

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

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

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