我可以同时具有协变和逆变的类型,即可以与子类型和超类型完全互换/互换吗? [英] Can I have a type that's both, covariant and contravariant, i.e. fully fungible/changeable with sub and super types?

查看:101
本文介绍了我可以同时具有协变和逆变的类型,即可以与子类型和超类型完全互换/互换吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以有一个既可以协变又可以协变的类型(现在暂时忘记它的语义)吗?

Can I have a type (for now forgetting its semantics) that can be covariant as well as contravariant?

例如:

public interface Foo<in out T>
{
    void DoFooWith(T arg);
}

请访问Eric Lippert的博客,了解C#4.0中的变化

Off to Eric Lippert's blog for the meat and potatoes of variance in C# 4.0 as there's little else anywhere that covers adequate ground on the subject.

无论如何,我还是尝试了一下,不仅不允许这样做那,但它告诉我,我遗漏了整个要点。我需要理解只读,只写和方差之间的联系。

I tried it out anyway, not only does it not allow that, but it tells me I am missing the whole point. I need to understand the link between read-only, write-only and variance.

我想我还有更多的阅读要做。

I guess I got some more reading to do.

但是与此同时,欢迎任何简短的顿悟式回答。

But any short, epiphany inducing answers are welcome, meanwhile.

推荐答案

不,您不能那样做。

假设这是合法的。您制作了 IFoo< Giraffe> 。由于IFoo在T中是协变的,因此可以通过类型安全的引用转换将其转换为 IFoo< object> 。由于它是互变的,因此可以将其转换为 IFoo< Banana> IFoo< T> 有什么可能的语义,以便能够通过引用转换将IFoo of Giraffes转换为Bananas IFoo是有意义的?长颈鹿和香蕉除了参考类型外没有其他共同点。您不可能在 IFoo< Banana> 上有一个返回香蕉的方法,因为它实际上可能是 IFoo< Giraffe> ;实现的作者如何知道要分发香蕉?出于相同的原因,您可能无法在 IFoo< Banana> 上使用采用香蕉的方法。 IFoo< Giraffe> 的实现者希望您递给他一头长颈鹿。

Suppose that were legal. You make an IFoo<Giraffe>. Since IFoo is covariant in T, you can convert it via typesafe reference conversion to IFoo<object>. Since it is contravariant, you can convert that to IFoo<Banana>. What possible semantics are there for IFoo<T> such that it makes sense to be able to convert an IFoo of Giraffes to an IFoo of Bananas via reference conversion? Giraffes and Bananas have nothing in common other than being reference types. You cannot possibly have a method on IFoo<Banana> that returns a Banana, because it might actually be an implementation of IFoo<Giraffe>; how would the author of the implementation know to hand out a Banana? You cannot possibly have a method on IFoo<Banana> that takes a Banana for the same reason; the implementor of IFoo<Giraffe> is expecting you to hand him a Giraffe.

这是另一种看待方式它:

Here's another way of looking at it:


  • 在T中意味着(大致) T仅出现在输入位置。

  • 输出T表示(大致) T仅出现在输出位置。

因此, in out T的意思是……什么?正如我们已经看到的,它仅表示 T根本不在任何方法或属性中出现。 在T中创建永不使用T的泛型类型有什么意义?

Therefore "in out T" would mean... what? As we've seen already, it can only mean "T does not appear at all in any method or property." What's the point of making a generic type in T where you never use T?

这篇关于我可以同时具有协变和逆变的类型,即可以与子类型和超类型完全互换/互换吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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