C#协变抗变

来源:互联网 发布:保险从业人员数据 编辑:程序博客网 时间:2024/06/14 04:16
using System;using System.Collections;using System.Collections.Generic;using System.Linq;using System.Text;namespace Example{    public class Shape         //形状基类    {        public double Width { get; set; }        public double Height { get; set; }            }    public class Rectangle : Shape   //矩形子类    {        public void Sum()        {            Console.WriteLine(Width + Height);        }    }    public interface IIndex<out T>      //接口,通过不同的类实现接口的内容,通过不同类的接口实现部分来达到接口的多态功能    {   //接口是协变的,即同子类转换为父类的方向是一致的,意味着返回类型只能是T        T this[int index] { get; }       //this代表接口        int Count { get; }    }    public interface IDisplay<in T>    //泛型接口是抗变的,T只能做为其方法的输入    {        void Show(T item);    }    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 ShapeDisplay : IDisplay<Shape>    {        public void Show(Shape s)        {            Console.WriteLine("{0}Width:{1},Height:{2}", s.GetType().Name, s.Width, s.Height);        }    }    class Program    {        static void Main()        {            RectangleCollection rectangles = RectangleCollection.GetRectangles();  //建立一个类实例            IIndex<Shape> shapes = rectangles;     //实现接口,此时接口的内容相当于下面注释掉的代码            for (int i = 0; i < shapes.Count; i++)            {                //shapes[i]为Rectangle类型                Console.WriteLine("{0},{1},{2}", shapes[i].Height, shapes[i].Width, shapes[i].GetType());            }        /*public Shape this[int index]        {            get            {                if (index < 0 || index > data.Length)                {                    throw new ArgumentOutOfRangeException("index");                }                return data[index];            }        }        public int Count        {            get            {                return data.Length;            }        }*/            IDisplay<Shape> shapeDisplay = new ShapeDisplay();   //建立一个实例,此时接口函数为void Show(Shape item);            IDisplay<Rectangle> rectangleDisplay = shapeDisplay;//此时接口函数转换为void Show(Rectangle item);            rectangleDisplay.Show(rectangles[0]);        }    }}

0 0
原创粉丝点击