static void Main(string[] args) { IIndex<Rectangle> rectangles = RectangleCollection.GetRectangles(); IIndex<Shape> shapes = rectangles; Console.ReadKey(); } public interface IIndex<out T> { T this[int index] { get; } int Count { get; } } public class RectangleCollection : IIndex<Rectangle> { private Rectangle[] data = new Rectangle[3] { new Rectangle{Width=2,Height=3}, new Rectangle{Width=3,Height=7}, new Rectangle{Width=4.5,Height=2.9} }; private static RectangleCollection coll; public static RectangleCollection GetRectangles() { return coll ?? (coll = new RectangleCollection()); } public Rectangle this[int index] { get { if (index < 0 || index > data.Length) { throw new ArgumentOutOfRangeException("index"); } return data[index]; } } public int Count { get { return data.Length; } } } public class Shape { public double Width { get; set; } public double Height { get; set; } public override string ToString() { return String.Format("width:{0},height:{1}", Width, Height); } } public class Rectangle : Shape { }
协变:
static void Main(string[] args) { IIndex<Rectangle> rectangles = RectangleCollection.GetRectangles(); IDisplay<Shape> shapeDisplay = new ShapeDisplay(); IDisplay<Rectangle> rectangleDisplay = shapeDisplay; rectangleDisplay.Show(rectangles[0]); Console.ReadKey(); } public interface IDisplay<in T> { void Show(T item); } public class ShapeDisplay : IDisplay<Shape> { public void Show(Shape item) { Console.WriteLine("{0} width:{1},height:{2}", item.GetType().Name, item.Width, item.Height); } }
抗变: