我在编译时收到以下错误消息:
“无效方差:类型参数‘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 RepositoryDerived1();
但是它在 IRepository 类上给出了编译时错误。
如果我从 IRepository 类中删除“out”关键字,它会给我另一个错误
“RepositoryDerived1”无法转换为“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/