简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM