How to fix this error? Invalid variance: The type parameter 'T' must be invariantly valid on

*爱你&永不变心* 提交于 2019-12-23 13:24:29

问题


I'm having the below error message at compile time:

"Invalid variance: The type parameter 'T' must be invariantly valid on 'ConsoleApplication1.IRepository.GetAll()'. 'T' is covariant."

and the below is my code:

 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();
    }
}

What I would need is to be able to use the above class like this:

IRepository repository;

or

RepositoryBase repository;

Then I'd like to be able to assign something like this:

repository = new RepositoryDerived1();

But it gives compile time error on the IRepository class.

If I remove the "out" keyword from the IRepository class, it gives me another error that

"RepositoryDerived1" can not be converted to "IRepository".

Why and how to fix it?

Thanks


回答1:


IList<T> is not covariant. If you change the IList<T> to IEnumerable<T>, and remove the : new() constraint from IRepository<out T> (as the abstract base class doesn't satisfy that) it'll work:

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();
    }
}


来源:https://stackoverflow.com/questions/7416705/how-to-fix-this-error-invalid-variance-the-type-parameter-t-must-be-invarian

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!