从泛型类派生的类中缺少构造函数。

3

我试图创建一个基于这篇文章 的通用LINQ-TO-SQL仓库,基本上让你定义一个通用的基础仓库类,然后你可以通过派生自通用基础类来定义所有实际的仓库类。

我想要使用带有或不带有数据上下文的仓库选项,因此我决定在通用基类中创建两个构造函数:

  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
   }

为了使用它,我需要派生出我的实际仓库类:

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

现在,如果我尝试使用这个参数:
AppDataContext db = new AppDataContext();
TeamRepository repos=new TeamRepository(db);

我遇到了这个错误:'App.Models.TeamRepository'不包含一个带有1个参数的构造函数
看起来在C#中你不能继承构造函数,那么你怎样编写代码才能调用:TeamRepository()或TeamRepository(db)呢?
2个回答

6

派生类不会自动继承任何基类的构造函数,您需要明确定义它们。

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

需要注意的是,如果基类定义了(隐式或显式)一个可访问的默认构造函数,派生类的构造函数会在未显式调用构造函数的情况下自动调用它。


M: "派生类不会自动继承基类的。" 应该是 "派生类不会自动继承基类的构造函数。" - Merlyn Morgan-Graham

1

你说得对,C#中的构造函数不会被传递到子类中。你需要自己声明它们。在你的例子中,你需要为每个仓库暴露两个构造函数。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接