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
        {
    
        }
    
    }
    

      

  • 相关阅读:
    设计模式
    雨夹雪背景特效
    lottie-前端实现AE动效
    响应式布局实现原理
    关于小程序(含uniapp)中使用npm模块
    使用脚手架快速搭建React项目
    vue项目接入友盟统计站点数据
    git常用命令
    uniapp请求方法的封装
    小程序获取用户登录及手机号登录
  • 原文地址:https://www.cnblogs.com/xiaobing1/p/9898114.html
Copyright © 2011-2022 走看看