接口的协变与抗变

一,泛型接口中泛型类型的前面标有in和out关键字 其中标有out关键字的参数我协变,而输出的结果就是抗变,IN与之相反。

如下代码:

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

namespace KongzhiTai
{
    class Program
    {
        static void Main(string[] args)
        {
            //IIndex<Rectangle> rectangles = RectangleCollection.Getrectangles();//
            //IIndex<Shape> shapes = rectangles;
            //for (var i = 0; i < shapes.Count; i++)
            //{
            // Console.WriteLine(shapes[i]);
            //}
            //Console.ReadKey();
            Rectangle re = new Rectangle();
            re.Heigh = 11;
            re.Width = 11;
            Console.WriteLine(re);
            Console.ReadKey();

        }

    }

    //创建实现接口 IIndex的RectangleCollection类
    public class RectangleCollection : IIndex<Rectangle>
    {
        //创建rectangle集合
        private readonly Rectangle[] _data = new Rectangle[3]
        {
        new Rectangle{Heigh=11,Width=11},
        new Rectangle{Heigh=22,Width=22},
        new Rectangle{Heigh=33,Width=33}
        };
        public static RectangleCollection Getrectangles()
        {
            return new RectangleCollection();
        }
        public Rectangle this[int index]
        {
            get { return _data[index]; }
        }
        //创建的rectangle的长度
        public int Count
        {
            get { return _data.Length; }
        }
    }
    //如果泛型类型用out关键字标注,泛型接口就是协变的。这也意味着返回类型只能是T
    public interface IIndex<out T>
    {
        T this[int index] { get; }//返回值是T类型的索引器
        int Count { get; }//Count属性
    }
    public class Shape
    {
        public double Heigh { get; set; }
        public double Width { get; set; }
        public override string ToString()
        {
            return string.Format("Width:{0},Height:{1}", Width.ToString(), Heigh.ToString());
        }

    }
    public class Rectangle : Shape
    {

    }

}

  

原文地址:https://www.cnblogs.com/xiaobing1/p/9898114.html