zoukankan      html  css  js  c++  java
  • 委托的协变与逆变代码

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace ConsoleApplication1
    {
        public delegate T Function<out T>();    //泛型委托   out关键字:基于协变的变体
        //public delegate Strong Function2();     //普通委托
        public delegate void Operate<in T>(T instance);//泛型委托   in关键字:基于逆变的变体
    
        public class Program
        {
            static void Main(string[] args)
            {
                //协变委托
                Function<Strong> funStrong = new Function<Strong>(GetInstance);
                Function<Weak> funWeak = funStrong;
                Weak weak = funWeak();
    
                //逆变委托
                Operate<Weak> opWeak = new Operate<Weak>(DoSth);
                Operate<Strong> opStrong = opWeak;
                opStrong(new Strong());
            }
    
            static Strong GetInstance()
            {
                return new Strong();
            }
    
            static void DoSth(Weak weak) { 
                //...
            }
        }
    
        /// <summary>
        /// 强类型
        /// </summary>
        class Weak { }
    
        /// <summary>
        /// 弱类型
        /// </summary>
        class Strong : Weak
        { 
        
        }
    }
    

  • 相关阅读:
    idea git 操作
    1
    python 迭代器/生成器/迭代对象
    python 中的type
    systemd 配置文件
    python 中类的初始化过程
    mysql主从错误180301
    从零开始搭建k8s-20180301
    kubernetes role
    Java程序员毕业两年自述
  • 原文地址:https://www.cnblogs.com/lingyuan/p/1955338.html
Copyright © 2011-2022 走看看