.NET 4引入协方差.我想这是有用的毕竟,MS经历了将其添加到C#语言的所有麻烦.但是,为什么协方差比较好的旧多态性更有用?
我写了这个例子来了解为什么我应该实现协方差,但我还是不明白.请启发我
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(); } } }
解决方法
考虑一个API,要求IContainer< Shape>:
public void DrawShape(IContainer<Shape> container>) { /* ... */ }
您有一个容器< Circle>.你如何将你的容器传递给DrawShape API?没有协方差,Container< Circle>不能转换为IContainer< Shape>,要求您重写类型或提出其他解决方法.
这在使用大量通用参数的API中并不常见.