20250606-C#知识:委托和事件
C#知识:委托和事件
使用委托可以很方便地调用多个方法,也方便将方法作为参数进行传递
1、委托
- 委托是方法的容器
- 委托可以看作一种特殊的类
- 先定义委托类,再用委托类声明委托变量,委托变量可以存储方法
delegate int Calculate(int a, int b);
Calculate calculate;
calculate = Add;
calculate(5, 3);
- 委托可以存储多个方法
calculate = Add;
calculate += Sub;
calculate += Mul;
- 委托必须先赋值,然后使用+=添加方法或使用-=删除方法
- 删除方法,可以随机删除方法
calculate -= Add;
calculate(5, 3);
//清空
calculate = null;
- 委托可以有泛型
delegate T CalculatePlus<T>(T a, T b);
CalculatePlus<int> calculatePlus;
calculatePlus = Add;
calculatePlus(6, 2);
- 系统提供了两种委托Action和Func
- 系统提供的委托支持泛型,一般够用
- 无返回值Action
Action<string> myAction = Speak;
myAction.Invoke("Sleep is fine");
- 有返回值Func,最后一个泛型参数为返回类型
Func<float, int, string> myFunc = Move;
myFunc(100, 6);
2、事件
- 青春迷你版委托(受限制的委托)
- 创建委托变量时在前面加上event关键字
public event Action<string> myEvent;
- 与委托相比,不能在创建事件变量的类外赋值和调用
- 使用事件更安全
- 事件只能作为成员存在于类、接口和结构体中
class TestEvent
{public Action<string> myDelegate;public event Action<string> myEvent;public void InitializeEvent(){myEvent = null;}
}
TestEvent testEvent = new TestEvent();
//testEvent.myEvent = Speak; //报错
testEvent.myDelegate = Speak;testEvent.InitializeEvent();
testEvent.myEvent += Speak;//testEvent.myEvent("歪比巴卜"); //报错
testEvent.myDelegate("Ohhhhhhhhhh no!");
3、完整代码示例
namespace LearnDelegateAndEvent
{delegate int Calculate(int a, int b);delegate T CalculatePlus<T>(T a, T b);class TestEvent{public Action<string> myDelegate;public event Action<string> myEvent;public void InitializeEvent(){myEvent = null;}}internal class Program{static int Add(int a, int b){int result = a + b;Console.WriteLine($"ADD:{result}");return result;}static int Sub(int a, int b){int result = a - b;Console.WriteLine($"SUB:{result}");return a - b;}static int Mul(int a, int b){int result = a * b;Console.WriteLine($"MUL:{result}");return a * b;}static void Speak(string word){Console.WriteLine($"I want to say {word}");}static string Move(float speed, int seconds){string result = $"Move:{speed * seconds}";Console.WriteLine(result);return result;}static void Main(string[] args){//委托按照添加顺序执行方法Calculate calculate;//添加方法calculate = Add;calculate += Sub;calculate += Mul;calculate(1, 2);//删除方法,可以随机删除方法calculate -= Add;calculate(5, 3);calculate = null;//泛型委托CalculatePlus<int> calculatePlus;calculatePlus = Add;calculatePlus(6, 2);//系统委托Action<string> myAction = Speak;myAction.Invoke("Sleep is fine");//有返回值,最后一个泛型参数为返回类型Func<float, int, string> myFunc = Move;myFunc(100, 6);Console.WriteLine("==========================");//事件TestEvent testEvent = new TestEvent();//testEvent.myEvent = Speak; //报错testEvent.myDelegate = Speak;testEvent.InitializeEvent();testEvent.myEvent += Speak;//testEvent.myEvent("歪比巴卜"); //报错testEvent.myDelegate("Ohhhhhhhhhh no!");}}
}
输出:
ADD:3
SUB:-1
MUL:2
SUB:2
MUL:15
ADD:8
I want to say Sleep is fine
Move:600
==========================
I want to say Ohhhhhhhhhh no!
4、参考资料
- 《唐老狮C#》
本文结束,感谢您的阅读~