![](/img/trans.png)
[英]c# compiler error 'Parameter must be input safe. Invalid variance. The type parameter 'T' must be invariantly valid on Expression<TDelegate> '
[英]How to fix this error? Invalid variance: The type parameter 'T' must be invariantly valid on
我在編譯時遇到以下錯誤消息:
“無效的方差:類型參數'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>
,並從IRepository<out T>
刪除: new()
約束(因為抽象基類不滿足),它將起作用:
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();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.