问题描述
.NET 4引入了协方差.我想这很有用.毕竟,MS经历了将其添加到C#语言的所有麻烦.但是,为什么协方差比良好的旧多态性更有用?
.NET 4 introduces covariance. I guess it is useful. After all, MS went through all the trouble of adding it to the C# language. But, why is Covariance more useful than good old polymorphism?
我写了这个例子来理解为什么我应该实现协方差,但是我仍然不明白.请赐教.
I wrote this example to understand why I should implement Covariance, but I still don't get it. Please enlighten me.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Sample
{
class Demo
{
public delegate void ContraAction<in T>(T a);
public interface IContainer<out T>
{
T GetItem();
void Do(ContraAction<T> action);
}
public class Container<T> : IContainer<T>
{
private T item;
public Container(T item)
{
this.item = item;
}
public T GetItem()
{
return item;
}
public void Do(ContraAction<T> action)
{
action(item);
}
}
public class Shape
{
public void Draw()
{
Console.WriteLine("Shape Drawn");
}
}
public class Circle:Shape
{
public void DrawCircle()
{
Console.WriteLine("Circle Drawn");
}
}
public static void Main()
{
Circle circle = new Circle();
IContainer<Shape> container = new Container<Circle>(circle);
container.Do(s => s.Draw());//calls shape
//Old school polymorphism...how is this not the same thing?
Shape shape = new Circle();
shape.Draw();
}
}
}
推荐答案
考虑一个要求输入IContainer<Shape>
的API:
Consider an API which asks for an IContainer<Shape>
:
public void DrawShape(IContainer<Shape> container>) { /* ... */ }
您有一个Container<Circle>
.如何将容器传递给DrawShape
API?如果没有协方差,则类型Container<Circle>
不能转换为IContainer<Shape>
,需要重新包装类型或提出其他解决方法.
You have a Container<Circle>
. How can you pass your container to the DrawShape
API? Without covariance, the type Container<Circle>
is not convertible to IContainer<Shape>
, requiring you to rewrap the type or come up with some other workaround.
在使用大量通用参数的API中,这并不是一个罕见的问题.
This is not an uncommon problem in APIs that use a lot of generic parameters.
这篇关于协方差如何比多态性凉爽...而不是多余的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!