T必须是contravariantly有效 [英] T must be contravariantly valid

查看:155
本文介绍了T必须是contravariantly有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是不对的。

interface IRepository<out T> where T : IBusinessEntity
{
    IQueryable<T> GetAll();
    void Save(T t);
    void Delete(T t);
}



它说:

It says:

无效差异:类型参数'T'必须是'MyNamespace.IRepository.Delete(T)contravariantly有效。 'T'是协变

Invalid variance: The type parameter 'T' must be contravariantly valid on 'MyNamespace.IRepository.Delete(T)'. 'T' is covariant.

推荐答案

考虑会发生什么,如果编译器允许的:

Consider what would happen if the compiler allowed that:

interface IR<out T>
{
    void D(T t);
}

class C : IR<Mammal>
{
    public void D(Mammal m)
    {
        m.GrowHair();
    }
}
...
IR<Animal> x = new C(); 
// legal because T is covariant and Mammal is convertible to Animal
x.D(new Fish()); // legal because IR<Animal>.D takes an Animal

和你只是想上长出头发一条鱼。

And you just tried to grow hair on a fish.

停止是指T的输出位置仅用于。您正在使用它输入位置。

The "out" means "T is only used in output positions". You are using it in an input position.

这篇关于T必须是contravariantly有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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