文章目录
1. 委托
1.1 委托概述
  委托简介
 
// 声明一个public访问修饰符的 (具有输入字符串类型 + 返回整形数据类型) 的委托
public delegate int MyDelegate(string s); // 委托的模板
static int way1(string s){ // 定义符合委托模板的方法
    Console.WriteLine("way1: 传入的字符串为: " + s + ", 随后我即将返回整形数字1");
    return 1;
}
MyDelegate m1; // 通过委托模板实例化委托的容器
m1 = way1; // 往这个委托的容器当中放入方法
MyDelegate m1 = new MyDelegate(way1); // 等效于上述两个步骤之和
1.2 委托使用
using System;
namespace DelegateAppl {
    class TestDelegate {
        // 声明一个public访问修饰符的 (具有输入字符串类型 + 返回整形数据类型) 的委托模板
        public delegate int MyDelegate(string s);
        static int way1(string s){
            Console.WriteLine("way1: 传入的字符串为: " + s + ", 随后我即将返回整形数字1");
            return 1;
        }
        static void Main(){
            MyDelegate m1; // 通过委托模板获取委托的容器
            m1 = way1; // 往这个委托的容器当中放入方法
            m1("hi.."); // way1: 传入的字符串为: hi.., 随后我即将返回整形数字1
        }
    }
}
1.3 委托的传播

using System;
namespace DelegateAppl {
    class TestDelegate {
        public delegate int MyDelegate(string s);
        static int way1(string s){
            Console.WriteLine("way1: 传入的字符串为: " + s + ", 随后我即将返回整形数字1");
            return 1;
        }
        static int way2(string s) {
            Console.WriteLine("way2: 传入的字符串为: " + s + ", 随后我即将返回整形数字2");
            return 2;
        }
        static void Main(){
            MyDelegate m1; 
            m1 = way1;
            m1 += way2; // 或者可以先实例化一个新的MyDelegate m2 = way2; 再用 m1 += m2; 
            m1("hi.."); 
        }
    }
}
/*
way1: 传入的字符串为: hi.., 随后我即将返回整形数字1
way2: 传入的字符串为: hi.., 随后我即将返回整形数字2
 */
2. 匿名方法
2.1 匿名方法概述
  简要说明
 
public delegate int MyDelegate(string s);
MyDelegate m1 = delegate (string s) { // 匿名方法(省去方法的名字)
    Console.WriteLine(s);
    return 3;
};
2.2 匿名方法
using System;
namespace DelegateAppl {
    class TestDelegate {
        public delegate int MyDelegate(string s);
        static void Main(){
            MyDelegate m1 = delegate (string s) {
                Console.WriteLine(s);
                return 3;
            };
            int num = m1("hello world.....");
            Console.WriteLine(num);
        }
    }
}
/*
hello world.....
3
 */










