C#学习笔记【委托Delegate】

C# 委托(Delegate)

在 C# 中,委托(Delegate) 是一种类型安全的函数指针,它允许将方法作为参数传递给其他方法。

C# 中的委托(Delegate)类似于 C 或 C++ 中函数的指针。委托(Delegate) 是存有对某个方法的引用的一种引用类型变量,引用可在运行时被改变。

委托在 C# 中非常常见,用于事件处理、回调函数、LINQ 等操作。

所有的委托(Delegate)都派生自 System.Delegate 类。

声明委托(Delegate)

委托是一个引用类型,它定义了一个方法签名,可以用于存储指向该签名的方法。通过委托,你可以调用其他类中的方法。

委托声明决定了可由该委托引用的方法。委托可指向一个与其具有相同标签的方法。

声明委托的语法如下:

1
public delegate <return type> <delegate-name> <parameter list>

中文格式说明:

1
public delegate 返回类型 委托名(参数类型 参数名, ...);

例如以下代码,我们定义一个接受两个整数并返回一个整数的委托:

1
public delegate int MathOperation(int x, int y);

以下例子的委托可被用于引用任何一个带有一个单一的 string 参数的方法,并返回一个 int 类型变量。

1
public delegate int MyDelegate (string s);

实例化委托(Delegate)

一旦声明了委托类型,委托对象必须使用 new 关键字来创建,且与一个特定的方法有关。当创建委托时,传递到 new 语句的参数就像方法调用一样书写,但是不带有参数。例如:

1
2
3
4
public delegate void printString(string s);
...
printString ps1 = new printString(WriteToScreen);
printString ps2 = new printString(WriteToFile);

下面的实例演示了委托的声明、实例化和使用,该委托可用于引用带有一个整型参数的方法,并返回一个整型值。

> 实例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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 nc1 = new NumberChanger(AddNum);
NumberChanger nc2 = new NumberChanger(MultNum);
// 使用委托对象调用方法
nc1(25);
Console.WriteLine("Value of Num: {0}", getNum());
nc2(5);
Console.WriteLine("Value of Num: {0}", getNum());
Console.ReadKey();
}
}
}

当上面的代码被编译和执行时,它会产生下列结果:

1
2
Value of Num: 35
Value of Num: 175

委托的多播(Multicasting of a Delegate)

委托对象可使用 + 运算符进行合并。

一个合并委托调用它所合并的两个委托,只有相同类型的委托可被合并。

  • 运算符可用于从合并的委托中移除组件委托。

使用委托的这个有用的特点,您可以创建一个委托被调用时要调用的方法的调用列表,这被称为委托的 多播(multicasting),也叫组播。

下面的程序演示了委托的多播:

> 实例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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();
}
}
}

当上面的代码被编译和执行时,它会产生下列结果:

1
Value of Num: 75

委托(Delegate)的用途

下面的实例演示了委托的用法。委托 printString 可用于引用带有一个字符串作为输入的方法,并不返回任何东西。

我们使用这个委托来调用两个方法,第一个把字符串打印到控制台,第二个把字符串打印到文件:

> 实例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
using System;
using System.IO;

namespace DelegateAppl
{
class PrintString
{
static FileStream fs;
static StreamWriter sw;
// 委托声明
public delegate void printString(string s);

// 该方法打印到控制台
public static void WriteToScreen(string str)
{
Console.WriteLine("The String is: {0}", str);
}
// 该方法打印到文件
public static void WriteToFile(string s)
{
fs = new FileStream("c:\\message.txt", FileMode.Append, FileAccess.Write);
sw = new StreamWriter(fs);
sw.WriteLine(s);
sw.Flush();
sw.Close();
fs.Close();
}
// 该方法把委托作为参数,并使用它调用方法
public static void sendString(printString ps)
{
ps("Hello World");
}
static void Main(string[] args)
{
printString ps1 = new printString(WriteToScreen);
printString ps2 = new printString(WriteToFile);
sendString(ps1);
sendString(ps2);
Console.ReadKey();
}
}
}

当上面的代码被编译和执行时,它会产生下列结果:

1
The String is: Hello World

移除委托

如果你不再需要某个方法,可以通过 -= 运算符将该方法从委托链中移除。

> 实例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class Program
{
public delegate void PrintMessage(string message);

public static void PrintUpperCase(string message)
{
Console.WriteLine(message.ToUpper());
}

public static void PrintLowerCase(string message)
{
Console.WriteLine(message.ToLower());
}

public static void Main()
{
PrintMessage print = PrintUpperCase;
print += PrintLowerCase;

// 移除 PrintLowerCase 方法
print -= PrintLowerCase;

// 调用委托(只会调用 PrintUpperCase)
print("Hello, C#"); // 输出: HELLO, C#
}
}

委托和事件

委托常常与事件(Event)一起使用,事件是一种特殊类型的委托,用于发布和订阅机制。

在 C# 中,事件本质上就是一个封装了委托的类型,它用于响应程序中的某些操作。

> 实例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
public class Button
{
// 定义一个事件
public event EventHandler Click;

// 引发事件的方法
public void OnClick()
{
if (Click != null)
{
Click(this, EventArgs.Empty); // 调用事件
}
}
}

public class Program
{
public static void Main()
{
Button button = new Button();

// 订阅事件
button.Click += Button_Click;

// 引发事件
button.OnClick(); // 输出 "Button clicked!"
}

private static void Button_Click(object sender, EventArgs e)
{
Console.WriteLine("Button clicked!");
}
}

委托的类型

C# 提供了几种常见的委托类型:

1、Action

Action:代表不返回值的方法。可以接受最多 16 个参数。

1
2
Action<string> printMessage = Console.WriteLine;
printMessage("Hello");

2、Func

Func:代表有返回值的方法。最多接受 16 个参数,第一个参数是输入参数,最后一个参数是返回值类型。

1
2
Func<int, int, int> add = (x, y) => x + y;
Console.WriteLine(add(3, 4)); // 输出 7

3、Predicate

Predicate:代表返回 bool 值的方法,通常用于条件判断。

1
2
Predicate<int> isEven = x => x % 2 == 0;
Console.WriteLine(isEven(4)); // 输出 True

委托的注意事项

类型安全:委托是类型安全的,这意味着只有签名匹配的方法才能赋值给委托。

匿名方法和 lambda 表达式:你可以使用匿名方法或 lambda 表达式来创建委托实例,简化代码。

1
2
Func<int, int, int> add = (x, y) => x + y;
Console.WriteLine(add(5, 3)); // 输出 8

异步调用:可以将委托与 BeginInvoke 和 EndInvoke 方法一起使用,进行异步调用。

委托是 C# 中一个非常强大和灵活的特性,可以帮助实现事件驱动的编程、回调机制和函数式编程风格。它不仅提供了代码重用的能力,还提高了程序的模块化程度。理解和掌握委托的使用对于 C# 编程是非常重要的。

实例总结:

委托多播实例

例如小明叫小张买完车票,之后接着又让他带张电影票。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public delegate void DoSomeThing();
public class MrZhang {
public static void HelpWith(DoSomeThing callback) {
// 小张的唯一方法,帮别人做某事;
Console.WriteLine("小张帮====》");
callback();
}
}

public class MrMing
{
public static void BuyTicket() {
Console.WriteLine("小明买了一张火车票");
}
public static void BuyMovieTicket() {
Console.WriteLine("小明买了一张电影票");

}
public static void Main() {
// 定义两件事,是小明需要去做的事
DoSomeThing thing1 = new DoSomeThing(BuyTicket);
DoSomeThing thing2 = new DoSomeThing(BuyMovieTicket);
// 让小张去做这两件事
thing1 += thing2;
MrZhang.HelpWith(thing1);

Console.ReadKey();
}
}

输出结果:

1
2
3
小张帮====》
小明买了一张火车票
小明买了一张电影票