c# - 如何修复此错误?无效方差 : The type parameter 'T' must be invariantly valid on

标签 c# generics covariance contravariance

我在编译时收到以下错误消息:

“无效方差:类型参数‘T’必须在‘ConsoleApplication1.IRepository.GetAll()’上始终有效。‘T’是协变的。”

下面是我的代码:

 class Program
{

    static void Main(string[] args)
    {
        IRepository<BaseClass> repository;

        repository = new RepositoryDerived1<Derived1>();

        Console.ReadLine();
    }
}

public abstract class BaseClass
{

}

public class Derived1 : BaseClass
{

}

public interface IRepository<out T> where T: BaseClass, new()
{
    IList<T> GetAll();
}

public class Derived2 : BaseClass
{

}

public abstract class RepositoryBase<T> : IRepository<T> where T: BaseClass, new()
{
    public abstract IList<T> GetAll();
}

public class RepositoryDerived1<T> : RepositoryBase<T> where T: BaseClass, new()
{
    public override IList<T> GetAll()
    {
        throw new NotImplementedException();
    }
}

我需要的是能够像这样使用上面的类:

IRepository 仓库;

RepositoryBase 仓库;

然后我希望能够分配这样的东西:

repository = new RepositoryDe​​rived1();

但是它在 IRepository 类上给出了编译时错误。

如果我从 IRepository 类中删除“out”关键字,它会给我另一个错误

“RepositoryDe​​rived1”无法转换为“IRepository”。

为什么以及如何解决?

谢谢

最佳答案

IList<T>不是协变的。如果您更改 IList<T>IEnumerable<T> , 并删除 : new()来自 IRepository<out T> 的约束(因为抽象基类不满足)它会起作用:

public interface IRepository<out T> where T : BaseClass
{
    IEnumerable<T> GetAll();
}

public abstract class RepositoryBase<T> : IRepository<T> where T : BaseClass, new()
{
    public abstract IEnumerable<T> GetAll();
}

public class RepositoryDerived1<T> : RepositoryBase<T> where T : BaseClass, new()
{
    public override IEnumerable<T> GetAll()
    {
        throw new NotImplementedException();
    }
}

关于c# - 如何修复此错误?无效方差 : The type parameter 'T' must be invariantly valid on,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7416705/

相关文章:

c# - 在 linq 中检查字符串是否为 null 或为空

c# - 是否可以拦截 READ 操作?

c# - 控制台输出到文本框

c# - 与泛型一起使用时,Expression.Convert(..., someGenericType) 会抛出 ArgumentException

Scala 下限类型和协方差

c++ - 返回专用模板类的协变类型

c# - 没有切换功能的消息框对话框

java - map 上没有这个元素,为什么?

c# - 在通用提供程序中如何查找和编辑 T 的属性? (C#)

c# - 为什么 C# 在带有委托(delegate)的输入参数中使用逆变(而不是协方差)?