我有以下的階層結構如何將IRepository <Invoice>和IRepository <Estimate>作爲IRepository <SalesTransaction>進行抽象?
public abstract class SalesTransaction
{
}
public class Invoice : SalesTransaction
{
}
public class Estimate : SalesTransaction
{
}
public interface IRepostory<T>
{
T First(Expression<Func<T, bool>> predicate);
void Add(T item);
T Single(Expression<Func<T, bool>> predicate, bool disableTracking = false);
}
我可以以某種方式通過它鑄造IRepository<SalesTransaction>
抽象IRepository<Invoice>
和IRepository<Estimate>
?
IRepository<Invoice> invoiceRepository = /* Create instance */;
IRepository<SalesTransaction> salesTransaction = invoiceRepository;
上面的代碼不能編譯。是否有解決方法讓它能夠編譯和工作?
看看https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/covariance-contravariance/ – Nkosi
而這個https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/covariance-contravariance/creating-variant-generic-interfaces – Nkosi
它是否因爲您提到將其轉換爲SalesReceipt而不是編譯,但是繼承自SalesTransaction? – Tony