• 接口的协变与抗变


    一,泛型接口中泛型类型的前面标有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
        {
    
        }
    
    }
    

      

  • 相关阅读:
    (转)机器学习——深度学习(Deep Learning)
    (转)Deep Learning深度学习相关入门文章汇摘
    (转)Haar-like矩形遍历检测窗口演示Matlab源代码
    HTML5远程工具
    splinter操作ie浏览器
    Wechat login authorization(OAuth2.0)
    Message Queuing(MSMQ)
    Visual Studio2017 数据库架构比较
    Visual Studio2017 Remote Debugger
    搭建Spring Initializr服务器
  • 原文地址:https://www.cnblogs.com/xiaobing1/p/9898114.html
Copyright © 2020-2023  润新知