如何解决这个问题?无效的方差:类型参数'T'必须是有效目不暇接 [英] How to fix this error? Invalid variance: The type parameter 'T' must be invariantly valid on

查看:256
本文介绍了如何解决这个问题?无效的方差:类型参数'T'必须是有效目不暇接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在编译时以下错误消息:

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

无效的差异:类型参数'T'必须是'ConsoleApplication1.IRepository目不暇接有效。 '。'GETALL()T'是协变的

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

和下面的是我的代码:

 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库;

IRepository repository;

RepositoryBase库;

RepositoryBase repository;

然后我希望能够分配是这样的:

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

资料库=新RepositoryDe​​rived1();

repository = new RepositoryDerived1();

但它给人的IRepository类编译时错误

But it gives compile time error on the IRepository class.

如果。我删除从IRepository类的OUT的关键字,它给了我一个错误

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

RepositoryDe​​rived1不能被转换为IRepository。

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

为什么,以及如何解决它?

Why and how to fix it?

感谢

推荐答案

的IList< T> 不是协变的。如果你改变了的IList< T> 的IEnumerable< T> ,并删除: (作为抽象基类不满足的),它会工作从 IRepository<新的()约束>

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

这篇关于如何解决这个问题?无效的方差:类型参数'T'必须是有效目不暇接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆