zoukankan      html  css  js  c++  java
  • 委托和泛型

    1. 委托Delegate

      •    继承自MulticastDelegate
      •    声明委托定义签名:
        public delegate int DemoDelegate(int num1, int num2);
      •   使用相同签名的方法实例化委托:
        int Sum(int input1, int input2){ return input1 + input1; }
        DemoDelegate demo1 = Sum;
      •   使用匿名方法实例化委托:
        DemoDelegate demo2 = delegate(int input1, int input2)
        {
            return input1 * input2;
        }
      • 使用lambda表达式实例化委托:
        DemoDelegate demo3 = (int input1, int input2) => input1 - input2;
      • 调用方法:
        int resultSum = demo(10, 20);         // result: 30
        int resultMultiply = demo(10, 20);    // result: 200
        int resultMinus = demo(10, 20);       // result: –10

    2. 泛型

      •    命名空间: System.Collections.Generic
      •    使用T作为参数放在尖括号中:
        public class DemoGeneric<T>{}
      • 使用List<T>不需要装箱操作和强制类型转换,效率高,编译时检查类型T
      • 约束:
        public class DemoGeneric<T> where T : struct {}    //  类型参数必须为值类型
        public class DemoGeneric<T> where T : class {}     //  类型参数必须为引用类型(如类、接口、委托、数组类型)
        public class DemoGeneric<T> where T : new() {}   //  类型必须具有无参public构造函数, 与其他约束组合使用必须最后制定
        public class DemoGeneric<T> where T : U {}         //  类型参数必须为U提供的参数或派生自U提供的参数
      • 可以是用反射获取泛型类型
  • 相关阅读:
    shell脚本执行错误:#!/bin/bash: No such file or directory
    odoo 主题中怎么添加多个代码块 (snippets)
    怎么使用 python 的 jieba 中文分词模块从百万数据中找到用户搜索最多的关键字
    odoo 网站上线后,怎么修改网站主题?
    阿里菜鸟网络春招 【部门直推】【22届校招实习】
    java jfreechart 折线图数据量大,X 轴刻度密密麻麻显示不下,或者省略号的解决办法
    java jfreechart 时序图横坐标显示,设置步数初始坐标不展示问题解决
    springboot2 整合 redis 并通过 aop 实现自定义注解
    java 线程池 Executors,ExecutorService
    git免密码clone push,多个git账号配置
  • 原文地址:https://www.cnblogs.com/jameslif/p/3663955.html
Copyright © 2011-2022 走看看