继承的 class 方法的可见性没有意义?

Visibility of inherited class methods does not make sense?

以下代码代表我在一个工作单元上的努力。

接口:

public interface IUnitOfWork
{
    IFieldRepository FieldRepository { get; }
    void Save();
}

public interface IFieldRepository
{
    IEnumerable<Field> GetAllFields( int page, int amount, string sortByKey, SortDirection sortDirection );
}

具体工作单元class:

public class EFUnitOfWork : IDisposable, IUnitOfWork
{
    private EFDbContext context = new EFDbContext();

    private IFieldRepository fieldRepository;

    public IFieldRepository FieldRepository
    {
        get
        {

            if( this.fieldRepository == null )
            {
                this.fieldRepository = new EFFieldRepository( context );
                // At this point i can see this.fieldRepository.Insert() absolutely fine
            }
            return fieldRepository;
        }
    }

    // ...

具体字段存储库:

public class EFFieldRepository : EFGenericRepository<Field>, IFieldRepository
{
    public EFFieldRepository( EFDbContext context )
        : base( context )
    {}

    // ...

具体通用存储库:

public class EFGenericRepository<TEntity> where TEntity : class
{
    internal protected EFDbContext context;
    internal protected DbSet<TEntity> dbSet;

    public EFGenericRepository( EFDbContext context )
    {
        this.context = context;
        this.dbSet = context.Set<TEntity>();
    }

    public virtual void Insert( TEntity entity )
    {
        dbSet.Add( entity );
    }

    // ...

控制器class:

public class FieldController : Controller
{
    IUnitOfWork unitOfWork;

    public FieldController( IUnitOfWork unitOfWork )
    {
        this.unitOfWork = unitOfWork;
    }

    // GET: Field
    public ActionResult List()
    {
        unitOfWork.FieldRepository.Insert( ... ); // This method isn't visible? But GetAllFields is visible
        return View();
    }
}

问题出现在我的控制器中,我无法访问应该从我的 EFFieldRepository?

继承的方法

如果你看一下 EFUnitOfWork.FieldRepository 里面的评论,那时候我可以看到他们

什么阻止继承的 class 显示其方法?

unitOfWork.FieldRepository 的类型为 IFieldRepository 所以只有 GetAllFields() 可见:

IFieldRepository repository = unitOfWork.FieldRepository;
repository.GetAllFields();

您需要将其转换为 EFGenericRepository<Field>, IFieldRepository不要这样做!)或将此方法添加到接口:

public interface IFieldRepository
{
    void Insert(Field entity);
}

virtual在这里没有任何区别,你可以删除它。


但是我会为所有存储库提供一个通用接口:

public interface IRepository<T>
{
    IEnumerable<T> GetAll(int page, int amount, string sortByKey, SortDirection sortDirection);
}

或其更好的版本修改为与 EF 一起使用:

public interface IRepository<T>
{
    IEnumerable<T> GetAll();

    IEnumerable<T> GetAll(int page, int amount, Expression<Func<IQueryable<T>, Func<T, object>, IEnumerable<T>>> sort);
}

用法:

repository.GetAll(x, y, (seq, p) => seq.OrderBy(p => p.Name));