zoukankan      html  css  js  c++  java
  • 泛型委托当参数传递

    假如有一个Person类:

    public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
        public string Title { get; set; }
    }

    执行一个方法:

    /// <summary>
    /// 传递一个泛型委托方法
    /// </summary>
    /// <param name="action"></param>
    public static void SetNum(Action<Person> action)
    {
        Person person = new Person();
        //前面的代码
        //......
        action(person);
        //后面的代码 
        //......
    }

    调用:

    static void Main(string[] args)
    {
        //第一种写法(写一个方法,然后当参数传进来)
        SetNum(Set1);
        //第二种写法(声明一个委托变量,赋一个匿名方法,然后当参数传进来)
        Action<Person> action = delegate(Person person) { person.Name = "Tom"; };
        SetNum(action);
        //第三种写法(直接new出一个泛型Action,然后赋一个匿名方法,全写)
        SetNum(new Action<Person>(delegate(Person person) { person.Name = "Name"; }));
        //第四种写法(直接new出一个匿名方法,简写版)
        SetNum(delegate(Person person) { person.Name = "Name"; });
        //第五种写法(用Lambda表达式)
        SetNum(u => u.Name = "Name");
    }
    
    public static void Set1(Person person)
    {
        person.Name = "Name";
    }
  • 相关阅读:
    ELK安装(ubuntu)
    Ubuntu18.04上安装java
    .net core跨平台的文件路径
    缺少vim
    docker进入容器
    docker删除名字为none的imgae
    Ubuntu18.04上安装Docker-Compose
    Java类的反射
    Java常用类(二) Scanner类和大数类
    Java常用类(一)Math类和Random类
  • 原文地址:https://www.cnblogs.com/genesis/p/6238488.html
Copyright © 2011-2022 走看看