簡體   English   中英

如何解決這個錯誤? 方差無效:類型參數“T”必須是無效的

[英]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 RepositoryDe​​rived1();

但是它給IRepository類帶來了編譯時錯誤。

如果我從IRepository類中刪除“out”關鍵字,它會給我另一個錯誤

“RepositoryDe​​rived1”無法轉換為“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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM