简体   繁体   中英

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.

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

So, it looks like you cant inherit constructors in C#, so, how would you code this so I can call: TeamRepository() or 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. You'll have to declare them yourself. In your example, you'll need to surface two constructors for each of your repositories.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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