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> G开发者_开发百科etAll();
}
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();
}
}
精彩评论