泛型的协变out和抗变in

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RectangleCollection
{
    class Program
    {
        static void Main(string[] args)
        {
            IIndex<Rectangle> rectangles = RectangleCollection.GetRectangles();
            IIndex<Shape> shapes = rectangles;
            for (int i = 0; i < shapes.Count; i++)
            {
                Console.WriteLine(shapes[i]);
            }
            IDisplay<Shape> shapeDisplay = new ShapeDisplay();
            IDisplay<Rectangle> rectangleDisplay = shapeDisplay;
            rectangleDisplay.Show(rectangles[0]);
        }
    }

    /// <summary>
    /// 抗变
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public interface IDisplay<in T>
    {
        void Show(T item);
    }
    public class ShapeDisplay : IDisplay<Shape>
    {
        public void Show(Shape s)
        {
            Console.WriteLine("{0} Width: {1}, Height: {2}", s.GetType().Name, s.Width, s.Height);
        }
    }
    /// <summary>
    /// 协变
    /// </summary>
    /// <typeparam name="T"></typeparam>
    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 { Height=2, Width=5},
            new Rectangle { Height=3, Width=7},
            new Rectangle { Height=4.5, Width=2.9}
        };
        public static RectangleCollection GetRectangles()
        {
            return 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
    {
    }
}

 

posted on 2012-12-19 21:55  R.Ray  阅读(140)  评论(0)    收藏  举报

导航