简体   繁体   English

缺少从泛型类中获取的类中的构造函数

[英]Missing constructor in a class derrived from a generic class

I'm trying to create a generic LINQ-TO-SQL repository based on this post which basically lets you define a generic base repository class, then you can define all of your actual repository classes by deriving from the generic base. 我正在尝试基于这篇文章创建一个通用的LINQ-TO-SQL存储库,它基本上允许您定义通用基础存储库类,然后您可以通过从通用基础派生来定义所有实际存储库类。

I want the option of using a repository with or without passing in the data context, so I decided to create two constructors in the generic base class: 我希望选择使用存储库,无论是否传入数据上下文,因此我决定在通用基类中创建两个构造函数:

  public abstract class GenericRepository<T, C>
        where T : class
        where C : System.Data.Linq.DataContext, new()
    {
        public C _db;

        public GenericRepository()
        {
            _db = new C();
        }


        public GenericRepository(C db)
        {
            _db = db;
        }


        public IQueryable<T> FindAll()

    ... and other repository functions
   }

To use it, I would derrive my actual repository class: 要使用它,我会浏览我的实际存储库类:

public class TeamRepository : GenericRepository<Team, AppDataContext> { }

Now, if I try to use this with a parameter: 现在,如果我尝试将其与参数一起使用:

AppDataContext db = new AppDataContext();
TeamRepository repos=new TeamRepository(db);

I get the error: 'App.Models.TeamRepository' does not contain a constructor that takes 1 arguments 我收到错误: 'App.Models.TeamRepository'不包含带有1个参数的构造函数

So, it looks like you cant inherit constructors in C#, so, how would you code this so I can call: TeamRepository() or TeamRepository(db) 所以,看起来你不能继承C#中的构造函数,那么,你将如何编写代码以便我可以调用:TeamRepository()或TeamRepository(db)

Derived classes do not automatically inherit any base class's constructors, you need to explicitly define them. 派生类不会自动继承任何基类的构造函数,您需要显式定义它们。

public class TeamRepository : GenericRepository<Team, AppDataContext>
{
    public TeamRepository() : base() { }
    public TeamRepository(AppDataContext db) : base(db) { }
}

Do note however that if the base class defines (implicitly or explicitly) an accessible default constructor, constructors of the derived class will implicitly invoke it unless the constructor is invoked explicitly. 但请注意,如果基类定义(隐式或显式)可访问的默认构造函数,派生类的构造函数将隐式调用它,除非显式调用构造函数。

You're correct, constructors in C# are not bubbled up into subclasses. 你是对的,C#中的构造函数不会冒泡到子类中。 You'll have to declare them yourself. 你必须自己申报。 In your example, you'll need to surface two constructors for each of your repositories. 在您的示例中,您需要为每个存储库显示两个构造函数。

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

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