从接口重写任务



假设我有这样一个接口:

public interface IGenericRepository<T> where T : class, IDto, new()
{
...
public virtual async Task<IEnumerable<T>> GetAllComplexAsync() =>
await GetAllComplexAsync(o => true);
public virtual async Task<IEnumerable<T>> GetAllComplexAsync(
Expression<Func<T, object>> orderByExpr,
bool descending = false) =>
await GetAllComplexAsync(o => true, orderByExpr, descending);
public virtual async Task<IEnumerable<T>> GetAllComplexAsync(Expression<Func<T, bool>> whereExpr) =>
await GetAllComplexAsync(whereExpr, o => true);
public Task<IEnumerable<T>> GetAllComplexAsync(
Expression<Func<T, bool>> whereExpr,
Expression<Func<T, object>> orderByExpr,
bool descending = false);
}

然后我在泛型方法中实现它:

public class GenericRepository<T> : IGenericRepository<T> where T : class, IDto, new()
{
...
public virtual Task<IEnumerable<T>> GetAllComplexAsync(
Expression<Func<T, bool>> whereExpr,
Expression<Func<T, object>> orderByExpr,
bool descending = false) => throw new NotImplementedException();
}

,这需要在存储库中重写,但这里我得到错误:没有找到合适的方法来覆盖

public class SupplierRepository : GenericRepository<SupplierDto>
{
...
public override async Task<IEnumerable<SupplierDto>> GetAllComplexAsync()
{
return await _context.Suppliers
.AsNoTracking()
.Include(o => o.MachineTypes)
.ToListAsync();
}
}

我想在大多数任务中使用泛型,但其中一些更复杂(如包括等),这就是为什么我想在final类中重写它们。

我做错了什么?

您正在使用c# 8的一个新特性,称为默认接口方法。与大多数人期望的不同,实现接口的类不会继承该方法的接口默认实现。这在c# 8特性文档中有解释。

因此,GenericRepository类没有您试图在SupplierRepository中覆盖的GetAllComplexAsync()方法。

我们可以这样演示:

IGenericRepository<SupplierDto> x = new GenericRepository<SupplierDto>();
//this will work, and will use the interface's implementation
var result = await x.GetAllComplexAsync();
GenericRepository<SupplierDto> y = new GenericRepository<SupplierDto>();
//this will not compile, as the GenericRepository does not have that method 
var result2 = await y.GetAllComplexAsync();

最新更新