C#隐藏继承成员

时间:2013-04-12 13:45:41

标签: c# oop interface

我有这个设置并获得编译器警告“......隐藏继承的成员......”。我该如何解决?

public interface IRepository<T> where T : class
{
    IQueryable<T> GetAll();
    T GetById(int id);
}

public class EFRepository<T> : IRepository<T> where T : class
{
    public EFRepository(DbContext dbContext)
    {
        if (dbContext == null)
            throw new ArgumentNullException("dbContext");
        DbContext = dbContext;
        DbSet = DbContext.Set<T>();
    }

    protected DbContext DbContext { get; set; }

    protected DbSet<T> DbSet { get; set; }

    public virtual IQueryable<T> GetAll()
    {
        return DbSet;
    }

    public virtual T GetById(int id)
    {
        return DbSet.Find(id);
    }

}

public interface IProductRepository : IRepository<Product>
{
    // Product specific interface code here
}

public class ProductRepository : EFRepository<Product>, IProductRepository
{
    public ProductRepository(DbContext context) : base(context) { }

    public IQueryable<Product> GetAll()
    {
        return DbSet.Include("Table1").Include("Table2").AsQueryable();
    }
}

我收到编译器警告消息,但在运行应用程序时,出现StackOverflowException错误。添加新关键字仍会生成StackOverflowException错误。覆盖关键字不起作用。如果我注释掉ProductRepository GetAll()方法,一切都很好,花花公子。但我需要覆盖GetAll()方法。

感谢。

1 个答案:

答案 0 :(得分:3)

使用“new”关键字标记ProductRepository.GetAll:

public new IQueryable<Product> GetAll()
{
    return DbSet.Include("Table1").Include("Table2").AsQueryable();
}

这将隐藏方法EFRepository.GetAll()。

如果您希望两种方法都返回相同的结果,您也可以选择覆盖基本方法:

public override IQueryable<Product> GetAll()
{
    return DbSet.Include("Table1").Include("Table2").AsQueryable();
}