简体   繁体   English

泛型构造函数和继承

[英]Generic Constructors and Inheritance

I have a generic class with a class constraint on it. 我有一个具有类约束的泛型类。

public class MyContainer<T> where T : MyBaseRow

MyBaseRow is an abstract class which I also want to contain a member of some flavour of MyContainer. MyBaseRow是一个抽象类,我也想包含一个MyContainer风格的成员。

public abstract class MyBaseRow
{
    public MyContainer<MyBaseRow> ParentContainer;

    public MyBaseRow(MyContainer<MyBaseRow> parentContainer)
    {
        ParentContainer = parentContainer;
    }
}

I am having problems with the constructors of classes inherited from MyBaseRow eg. 我从MyBaseRow继承的类的构造函数遇到问题。

public class MyInheritedRowA : MyBaseRow
{
    public MyInheritedRowA(MyContainer<MyInheritedRowA> parentContainer)
    : base(parentContainer)
    { }
}

Won't allow MyInheritedRowA in the constructor, the compiler only expects and only allows MyBaseRow. 不允许在构造函数中使用MyInheritedRowA,编译器仅期望并且仅允许MyBaseRow。 I thought the generic class constraint allowed for inheritance? 我以为通用类约束允许继承? What am I doing wrong here and is there any way I can redesign these classes to get around this? 我在这里做错了什么,有什么办法可以重新设计这些类来解决这个问题? Many thanks in advance for any responses. 非常感谢您的任何答复。

Basically, you can't use generics that way, because the covariance system doesn't work that way with classes . 基本上,您不能以这种方式使用泛型,因为协方差系统不适用于class See here: http://geekswithblogs.net/abhijeetp/archive/2010/01/10/covariance-and-contravariance-in-c-4.0.aspx 看到这里: http : //geekswithblogs.net/abhijeetp/archive/2010/01/10/covariance-and-contravariance-in-c-4.0.aspx

You can however use an interface like this: 但是,您可以使用如下接口:

public interface MyContainer<out T> where T : MyBaseRow {

    }

And that code will compile. 该代码将编译。

You can make a covariant generic interface (C#4.0): 您可以创建协变通用接口(C#4.0):

  public interface IContainer<out T> where T : MyBaseRow
  {

  }

  public class MyContainer<T> : IContainer<T> where T : MyBaseRow
  {

  }

  public abstract class MyBaseRow
  {
    public IContainer<MyBaseRow> ParentContainer;

    public MyBaseRow(IContainer<MyBaseRow> parentContainer)
    {
      ParentContainer = parentContainer;
    }
  }

  public class MyInheritedRowA : MyBaseRow
  {
    public MyInheritedRowA(IContainer<MyInheritedRowA> parentContainer)
      : base(parentContainer)
    { }
  }

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

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