zoukankan      html  css  js  c++  java
  • 接口的协变与抗变

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

      

  • 相关阅读:
    【BZOJ】【1412】【ZJOI2009】狼和羊的故事
    【POJ】【2987】Firing
    【BZOJ】【1324】王者之剑
    【POJ】【2125】Destroying the Graph
    bzoj4870: [Shoi2017]组合数问题(DP+矩阵乘法优化)
    bzoj3810: [Coci2015]Stanovi(记忆化搜索)
    bzoj2120: 数颜色(BIT套主席树+set/分块)
    bzoj2144: 跳跳棋(二分/倍增)
    bzoj4552: [Tjoi2016&Heoi2016]排序(二分+线段树)
    bzoj4773: 负环(倍增floyd)
  • 原文地址:https://www.cnblogs.com/xiaobing1/p/9898114.html
Copyright © 2011-2022 走看看