协变和逆变的简单例子
有人能给我提供协变、逆变、不变性和反不变性的简单 C# 示例吗(如果存在的话)。
到目前为止我看到的所有示例都只是将一些对象转换为System.Object
。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
有人能给我提供协变、逆变、不变性和反不变性的简单 C# 示例吗(如果存在的话)。
到目前为止我看到的所有示例都只是将一些对象转换为System.Object
。
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(3)
我不知道“反不变性”是什么意思。其余的都很容易。
下面是协变的示例:
IEnumerable
接口是协变的。 Giraffe 可转换为 Animal 的事实意味着IEnumerable
可转换为IEnumerable
。由于List
实现IEnumerable
此代码在 C# 4 中成功;它在 C# 3 中会失败,因为IEnumerable
上的协变在 C# 3 中不起作用。这应该是有道理的。长颈鹿序列可以被视为动物序列。
下面是逆变的示例:
Action
委托是逆变的。 Frog 可转换为 Animal 的事实意味着Action
可转换为Action
。请注意,这种关系与协变关系的方向相反;这就是为什么它是“contra”变体。由于可转换性,此代码成功;在 C# 3 中它会失败。这应该是有道理的。该动作可以采取任何动物;我们需要一个可以采取任何青蛙的行动,并且可以采取任何动物的行动肯定也可以采取任何青蛙。
不变性的一个例子:
我们可以将
IList
传递给这个东西吗?不,因为有人要在其中写入老虎,而老虎不能出现在长颈鹿列表中。我们可以将IList
传递给这个东西吗?不,因为我们要从中读取哺乳动物,而动物列表可能包含青蛙。IList
是不变。它只能按其实际情况使用。有关此功能设计的一些其他想法,请参阅我的关于我们如何设计和构建它的系列文章。
http://blogs.msdn.com/b/ericlippert/存档/标签/协方差+和+逆变/
I have no idea what "contra-invariance" means. The rest are easy.
Here's an example of covariance:
The
IEnumerable<T>
interface is covariant. The fact that Giraffe is convertible to Animal implies thatIEnumerable<Giraffe>
is convertible toIEnumerable<Animal>
. SinceList<Giraffe>
implementsIEnumerable<Giraffe>
this code succeeds in C# 4; it would have failed in C# 3 because covariance onIEnumerable<T>
did not work in C# 3.This should make sense. A sequence of Giraffes can be treated as a sequence of Animals.
Here's an example of contravariance:
The
Action<T>
delegate is contravariant. The fact that Frog is convertible to Animal implies thatAction<Animal>
is convertible toAction<Frog>
. Notice how this relationship is the opposite direction of the covariant one; that's why it is "contra" variant. Because of the convertibility, this code succeeds; it would have failed in C# 3.This should make sense. The action can take any Animal; we need an action that can take any Frog, and an action that can take any Animal surely can also take any Frog.
An example of invariance:
Can we pass an
IList<Giraffe>
to this thing? No, because someone is going to write a Tiger into it, and a Tiger cannot be in a list of Giraffes. Can we pass anIList<Animal>
into this thing? No, because we are going to read a Mammal out of it, and a list of Animals might contain a Frog.IList<T>
is invariant. It can only be used as what it actually is.For some additional thoughts on the design of this feature, see my series of articles on how we designed and built it.
http://blogs.msdn.com/b/ericlippert/archive/tags/covariance+and+contravariance/
不变性(在这种情况下)是指不存在协变和逆变。所以“反不变性”这个词没有意义。任何未标记为
in
或out
的类型参数都是不变的。这意味着该类型参数既可以被使用也可以被返回。协方差的一个很好的例子是
IEnumerable
,因为IEnumerable
可以替换IEnumerable
。或者Func
返回T
类型的值。例如,
IEnumerable
可以转换为IEnumerable
,因为任何 Dog 都是动物。对于逆变,您可以使用任何消费接口或委托。我想到了
IComparer
或Action
。它们从不返回T
类型的变量,仅接收它。无论您希望在何处接收Base
,都可以传入Derived
。将它们视为仅输入或仅输出类型参数可以更容易理解 IMO。
不变量这个词通常不与类型方差一起使用,而是在类或方法不变量的上下文中使用,并表示保守的属性。请参阅 此 stackoverflow 线程,其中讨论了不变量和不变性之间的差异。
Invariance(in this context) is the absence of both co- and contra-variance. So the word contra-invariance doesn't make sense. Any type parameter that's not tagged as either
in
orout
is invariant. This means this type parameter can both be consumed and returned.A good example of co-variance is
IEnumerable<out T>
because anIEnumerable<Derived>
can be substituted for anIEnumerable<Base>
. OrFunc<out T>
which returns values of typeT
.For example an
IEnumerable<Dog>
can be converted toIEnumerable<Animal>
because any Dog is an animal.For contra-variance you can use any consuming interface or delegate.
IComparer<in T>
orAction<in T>
come to my mind. These never return a variable of typeT
, only receive it. Wherever you expect to receive aBase
you can pass in aDerived
.Thinking of them as input-only or output-only type-parameters makes it easier to understand IMO.
And the word invariants is typically not used together with type variance, but in the context of class or method invariants, and represents a conserved property. See this stackoverflow thread where the differences between invariants and invariance are discussed.
如果您考虑泛型的常规使用,您会经常使用接口来处理对象,但该对象是类的实例 - 您无法实例化该接口。使用简单的字符串列表作为示例。
我相信您知道使用
IList<>
而不是直接使用List
的优势。它允许控制反转,您可能决定不再使用List
,而是需要LinkedList
。上面的代码工作正常,因为接口和类的泛型类型是相同的:string
。如果你想创建一个字符串列表的列表,它可能会变得有点复杂。考虑这个例子:
这显然无法编译,因为泛型类型参数
IList
和List
不同。即使您将外部列表声明为常规类,例如List>
,它也不会编译 - 类型参数不匹配。这就是协方差可以发挥作用的地方。协方差允许您使用更多派生的类型作为此表达式中的类型参数。如果将 IList<> 设为协变,则可以简单地编译并解决问题。不幸的是,
IList<>
不是协变的,但它扩展的接口之一是:此代码现在可以编译,类型参数与上面的相同。
If you consider the regular use of generics, you regularly use an interface to handle an object, but the object is an instance of a class - you can't instantiate the interface. Use a simple list of strings as an example.
I'm sure you're aware of the advantages of using an
IList<>
rather than directly using aList<>
. It allows for inversion of control, and you might decide you don't want to use aList<>
any longer, but you want aLinkedList<>
instead. The above code works fine because the generic type of both the interface and class is the same:string
.It can get a bit more complicated if you want to make a list of list of string though. Consider this example:
This clearly won't compile, because the generic types arguments
IList<string>
andList<string>
are not the same. Even if you declared the outer list as a regular class, likeList<IList<string>>
, it would not compile - the type arguments do not match.So here's where covariance can help. Covariance allows you to use a more derived type as the type argument in this expression. If
IList<>
was made to be covariant, it would simlpy compile and fix the problem. Unfortunately,IList<>
is not covariant, but one the interfaces it extends is:This code now compiles, the type arguments are the same as they were above.