问题描述
有人能向我提供协方差,逆变,不变性和反不变性简单的C#示例(如果这样的东西存在的话)。
所有的样品我到目前为止看到刚刚铸造一些物体插入 System.Object的
。
I have no idea what "contra-invariance" means. The rest are easy.
Here's an example of covariance:
void FeedTheAnimals(IEnumerable<Animal> animals)
{
foreach(Animal animal in animals)
animal.Feed();
}
...
List<Giraffe> giraffes = ...;
FeedTheAnimals(giraffes);
The IEnumerable<T>
interface is covariant. The fact that Giraffe is convertible to Animal implies that IEnumerable<Giraffe>
is convertible to IEnumerable<Animal>
. Since List<Giraffe>
implements IEnumerable<Giraffe>
this code succeeds in C# 4; it would have failed in C# 3 because covariance on IEnumerable<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:
void DoSomethingToAFrog(Action<Frog> action, Frog frog)
{
action(frog);
}
...
Action<Animal> feed = animal=>{animal.Feed();}
DoSomethingToAFrog(feed, new Frog());
The Action<T>
delegate is contravariant. The fact that Frog is convertible to Animal implies that Action<Animal>
is convertible to Action<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:
void ReadAndWrite(IList<Mammal> mammals)
{
Mammal mammal = mammals[0];
mammals[0] = new Tiger();
}
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 an IList<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/
这篇关于合作和逆变简单的例子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!