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
*/
1.4 Action、Func 委托
Action委托是系统定义好的一系列可包含零个至多个参数且不带返回值的委托,常用于可以作为一些无需返回函数的存储
public delegate void Action<in T1,in T2,in T3 ...>(T1 arg1, T2 arg2, T3 arg3 ... );
==> in T 表示其参数类型是协变的,可以传入该类型或其子类型的值
Func委托是系统定义好的一系列可包含零个至多个参数且带一个返回值的委托,常用于可以作为一些多条件判断的容器存储
public delegate TResult Func<in T1,in T2,out TResult>(T1 arg1, T2 arg2);
==> in / out 都表示其类型为协变,可传入该类型或其子类型值, 常可设置输出类型为bool,作为多条件判断的委托
public static void Main(string[] args) {
Action<int, string> printString = (int x, string y)=>{
for(int i = 0; i < x; i ++ )
Console.WriteLine(y);
};
printString(2, "hello, world");
}
/*
hello, world
hello, world
*/
public static void Main(string[] args) {
Func<int, int, bool> func = (int x, int y) => {
return x > y ? true : false;
};
bool fg = func(2, 1);
Console.WriteLine(fg);
}
// True
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
*/