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

      

  • 相关阅读:
    页面中多个小图片元素合成一个大图片之后用CSS调用
    腾讯设计中心博客
    php 配置 curl , gd , openssl , mbstring
    Apache开启Rewrite环境
    防止入侵:My SQL各种攻击方法大全
    Css背景图合并工具功能增强
    php防CC攻击代码
    网站地址栏的图标代码
    PHP漏洞全解(一)PHP网页的安全性问题
    用PHP实现飞信api接口发飞信短信
  • 原文地址:https://www.cnblogs.com/xiaobing1/p/9898114.html
Copyright © 2011-2022 走看看