【问题标题】:How to Inherit from Generic Parent如何从通用父级继承
【发布时间】:2013-10-07 07:22:57
【问题描述】:

我有一个父类

public class GenericRepository<TEntity> where TEntity : class
    {
      //Implementation
    }

我想从这个类继承,但我似乎无法做到这一点,这是我的尝试

public class CustomerRepository<Customer> : GenericRepository<Customer> 
    {
       //implementation
    }

或者这个,

public class CustomerRepository<T> : GenericRepository<T> where T : new Customer()
    {

    }

或者这个

 public class CustomerRepository<T> : GenericRepository<CustomerRepository<T>> where T : CustomerRepository<T>
    {

    }

无论我做什么,我都会收到此错误。请告诉我如何从这个类继承,类共享相同的命名空间

错误“GenericRepository”不包含采用 0 个参数 CustomerRepository.cs 的构造函数

【问题讨论】:

    标签: c# generics inheritance


    【解决方案1】:

    听起来你想要一个从泛型类继承的非泛型类,像这样:

    public class CustomerRepository : GenericRepository<Customer>
    {
    }
    

    如果您希望这是一个缩小泛型参数类型的泛型类(只允许Customer 或派生类型):

    public class CustomerRepository<T> : GenericRepository<T>
        where T : Customer
    {
    }
    

    关于您的编译时错误:

    Error 'GenericRepository&lt;Customer&gt;' does not contain a constructor that takes 0 arguments

    这正是它所说的。您没有在派生类中定义构造函数,这意味着构造函数是隐式生成的,就好像您输入了这个:

    public CustomerRepository() : base() { }
    

    但是,基类 (GenericRepository&lt;Customer&gt;) 没有不带参数的构造函数。需要在派生类CustomerRepository中显式声明构造函数,然后在基类上显式调用构造函数。

    【讨论】:

      【解决方案2】:

      派生类中不需要重复类型参数,所以:

      public class CustomerRepository : GenericRepository<Customer> 
          {
             //implementation
          }
      

      是你需要的。

      【讨论】:

      • 谢谢,我刚试了,还是不能编译。完全相同的错误。我将重新启动 Visual Studio,看看是否有帮助。
      【解决方案3】:

      看来你的基类没有带参数的构造函数,如果是这样派生类必须声明a.constructor并调用带参数的基类构造函数。

      class MyBase { public MyBase(object art) { } }
      class Derived : MyBase {
          public Derived() : base(null) { }
       }
      

      在这个例子中,如果你从 Derived 中删除 ctor,你会得到同样的错误。

      【讨论】:

      • 谢谢,我实现了一个无参数的父构造函数并编译了它。谢谢
      【解决方案4】:

      使用可以写成:

       public class CustomerRepository : GenericRepository<Customer> 
       {
              //implementation
       }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-08-04
        • 1970-01-01
        • 1970-01-01
        • 2018-09-17
        • 2012-12-02
        • 1970-01-01
        • 1970-01-01
        • 2011-05-16
        相关资源
        最近更新 更多