c# - T 必须逆变有效

标签 c# .net generics covariance contravariance

这是怎么回事?

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/

相关文章:

java - 数组列表整数不起作用

java - 在非静态内部类中使用泛型

c# - 为什么抛出异常时应用程序不会崩溃

c# - Process.Start(/* pdf 路径 */) 不适用于 Windows 8 上的 Adob​​e Reader

c# - 使用 WinSCP .NET 程序集通过 FTPS(安全)发送文件

.net - 是否可以将系统.NET DLL调试为未优化?

c# - 如果浏览器可以显示 Accept-Encoding of deflate,它可以处理 .NET gzip 响应吗?

java - JLS 与类型转换相关

c# - 找不到类型或命名空间名称 'PrintDocument'(是否缺少 using 指令或程序集引用?)

c# - 我应该打更频繁、更小的电话吗?还是不太频繁的大电话?