这是怎么回事?
interface IRepository<out T> where T : IBusinessEntity
{
IQueryable<T> GetAll();
void Save(T t);
void Delete(T t);
}
它说:
Invalid variance: The type parameter 'T' must be contravariantly valid on 'MyNamespace.IRepository.Delete(T)'. 'T' is covariant.
最佳答案
考虑如果编译器允许会发生什么:
interface IR<out T>
{
void D(T t);
}
class C : IR<Mammal>
{
public void D(Mammal m)
{
m.GrowHair();
}
}
...
IR<Animal> x = new C();
// legal because T is covariant and Mammal is convertible to Animal
x.D(new Fish()); // legal because IR<Animal>.D takes an Animal
而您刚刚尝试在鱼身上长出毛发。
“out”的意思是“T只用在输出位置”。您正在输入位置使用它。
关于c# - T 必须逆变有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5041664/