委托是 C# 中的一种类型安全的函数指针,它允许将方法作为参数传递,或者将方法存储在变量中。委托是事件、异步编程和 LINQ 等功能的基础。
基本概念
委托声明
// 声明一个委托类型
public delegate void MyDelegate(string message);
委托实例化与使用
public class DelegateExample
{
public static void Main()
{
// 实例化委托
MyDelegate del = new MyDelegate(ShowMessage);
// 调用委托
del("Hello, Delegate!");
// 多播委托(组合委托)
del += AnotherMessage;
del("Now it's multicast!");
}
public static void ShowMessage(string message)
{
Console.WriteLine(message);
}
public static void AnotherMessage(string message)
{
Console.WriteLine("Another: " + message);
}
}
内置委托类型
C# 提供了几种内置的通用委托类型,无需自定义:
1.Action - 无返回值的方法
Action<string> action = Console.WriteLine;
action("Using Action delegate");
2.Func - 有返回值的方法
Func<int, int, int> add = (a, b) => a + b;
int result = add(5, 3); // 结果为8
3.Predicate - 返回bool的方法(通常用于过滤)
Predicate<string> isLong = s => s.Length > 5;
bool longEnough = isLong("Delegate"); // 返回true
匿名方法和 Lambda 表达式
匿名方法
MyDelegate del = delegate(string msg)
{
Console.WriteLine("Anonymous: " + msg);
};
del("Hello");
Lambda 表达式
MyDelegate del = msg => Console.WriteLine("Lambda: " + msg);
del("Hello");
多播委托
委托可以组合多个方法,按顺序调用:
Action<string> multiCast = Console.WriteLine;
multiCast += s => Console.WriteLine("Second: " + s);
multiCast += s => Console.WriteLine("Third: " + s);
multiCast("Multicast Message");
// 输出:
// Multicast Message
// Second: Multicast Message
// Third: Multicast Message
异步委托
委托可以异步调用:
public class AsyncDelegateExample
{
public static void Main()
{
Func<int, int, int> add = (a, b) =>
{
Thread.Sleep(1000); // 模拟耗时操作
return a + b;
};
// 异步调用
IAsyncResult result = add.BeginInvoke(5, 3, null);
Console.WriteLine("Doing other work...");
// 获取结果
int sum = add.EndInvoke(result);
Console.WriteLine($"Result: {sum}");
}
}
实际应用场景
1.事件处理:委托是 C# 事件系统的基础
2.LINQ:LINQ 查询大量使用 Func 和 Action 委托
3.异步编程:BeginInvoke/EndInvoke 模式
4.回调机制:将方法作为参数传递
注意事项
1.委托是引用类型
2.多播委托按添加顺序执行
3.可以使用 Delegate.Combine 和 Delegate.Remove 手动管理委托链
4.在多线程环境中使用委托时要注意线程安全问题
委托是 C# 中实现回调、事件和函数式编程风格的重要工具,理解委托对于掌握 C# 高级特性至关重要。