简体   繁体   中英

Why I can not call base constructor method with an argument?

public class GenericRepository<TEntity> where TEntity : class
{
    internal DbContext context;
    internal DbSet<TEntity> dbSet;

    public GenericRepository(DbContext context)
    {
        this.context = context;
        this.dbSet = context.Set<TEntity>();
    }
    //snip
}

public class MyRepository<TEntity> where TEntity : GenericRepository<TEntity>
{
        public MyRepository(DbContext context) : base(context){ }
        //snip
}

I extended the GenericRepository class, and to use base's member variables I need to call Base's constructor in child's constructor. But I got an error that says:

'object' does not contain a constructor that takes 1 arguments

Even though the GenericRepository has constructor.

What am I doing wrong?

Because your "base class" is object , not GenericRepository<TEntity> . You added a constraint on TEntity , you did not inherit from GenericRepository<TEntity> . Maybe you meant this:

public class MyRepository<TEntity> : GenericRepository<TEntity> where TEntity : class
{
    public MyRepository(DbContext context) : base(context){ }

You have to change MyRepository 's base class to GenericRepository<TEntity> Also you need to leave where TEntity : class restriction

public class MyRepository<TEntity> : GenericRepository<TEntity> where TEntity : class
{
    public MyRepository(object context)
        :base(context)
    {

    }
}

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