一、C# 委托、事件、回调 基础概念
1.委托是C#中实现事件、回调的基础
2.委托的概念:Delegate
C# 中的委托(Delegate)类似于 C 或 C++ 中函数的指针。
委托(Delegate) 是存有对某个方法的引用的一种引用类型变量。引用可在运行时被改变。
委托(Delegate)特别用于实现事件和回调方法。所有的委托(Delegate)都派生自 System.Delegate 类。
3.C# 事件 Event
事件(Event) 基本上说是一个用户操作,如按键、点击、鼠标移动等等,或者是一些提示信息,如系统生成的通知。应用程序需要在事件发生时响应事件。例如,中断。
C# 中使用事件机制实现线程间的通信。
事件是委托的一种使用类型
4. C# 回调 callback
C#中回调,是委托的另一种使用类型, 主要通过 没有Action ,Func 两个委托来实现回调。
Action :没有返回类型的委托
Func :需要有返回类型的委托。
5. Lamda表达式
Lamda 表达式 是匿名方法的一种,回调中最常用的形式。
更多 回调,lamda表达式使用参考: C# 匿名函数_C# 匿名函数使用整理
二、委托使用整理
1.声明委托
public delegate int MyDelegate (string s);
delegate <return type> <delegate-name> <parameter list>
2.实例化委托
public delegate void printString(string s);
...
printString ps1 = new printString(WriteToScreen);
printString ps2 = new printString(WriteToFile);
3.委托的多播 / 组播
using System;
delegate int NumberChanger(int n);
namespace DelegateAppl
{
class TestDelegate
{
static int num = 10;
public static int AddNum(int p)
{
num += p;
return num;
}
public static int MultNum(int q)
{
num *= q;
return num;
}
public static int getNum()
{
return num;
}
static void Main(string[] args)
{
// 创建委托实例
NumberChanger nc;
NumberChanger nc1 = new NumberChanger(AddNum);
NumberChanger nc2 = new NumberChanger(MultNum);
nc = nc1;
nc += nc2;
// 调用多播
nc(5);
Console.WriteLine("Value of Num: {0}", getNum());
Console.ReadKey();
}
}
}
更多: