如何修复此错误?无效的变化:类型参数“T”必须在

The*_*ght 4 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();
    }
}
Run Code Online (Sandbox Code Playgroud)

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

IRepository 存储库;

或者

RepositoryBase 存储库;

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

存储库 = 新 RepositoryDe​​rived1();

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

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

“RepositoryDe​​rived1”不能转换为“IRepository”。

为什么以及如何修复它?

谢谢

Mar*_*ell 5

IList<T>不是协变的。如果您将IList<T>to更改为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();
    }
}
Run Code Online (Sandbox Code Playgroud)