54、C# 委托 (Delegate)

委托是 C# 中的一种类型安全的函数指针,它允许将方法作为参数传递,或者将方法存储在变量中。委托是事件、异步编程和 LINQ 等功能的基础。

基本概念

委托声明

csharp 复制代码
// 声明一个委托类型
public delegate void MyDelegate(string message);

委托实例化与使用

csharp 复制代码
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 - 无返回值的方法

csharp 复制代码
Action<string> action = Console.WriteLine;
action("Using Action delegate");

2.Func - 有返回值的方法

csharp 复制代码
Func<int, int, int> add = (a, b) => a + b;
int result = add(5, 3); // 结果为8

3.Predicate - 返回bool的方法(通常用于过滤)

csharp 复制代码
Predicate<string> isLong = s => s.Length > 5;
bool longEnough = isLong("Delegate"); // 返回true

匿名方法和 Lambda 表达式

匿名方法

csharp 复制代码
MyDelegate del = delegate(string msg) 
{
    Console.WriteLine("Anonymous: " + msg);
};
del("Hello");

Lambda 表达式

csharp 复制代码
MyDelegate del = msg => Console.WriteLine("Lambda: " + msg);
del("Hello");

多播委托

委托可以组合多个方法,按顺序调用:

csharp 复制代码
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

异步委托

委托可以异步调用:

csharp 复制代码
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# 高级特性至关重要。

相关推荐
Jinkxs18 分钟前
JavaScript性能优化实战技术
开发语言·javascript·性能优化
future14121 小时前
游戏开发日记
数据结构·学习·c#
ydm_ymz1 小时前
C语言初阶4-数组
c语言·开发语言
presenttttt2 小时前
用Python和OpenCV从零搭建一个完整的双目视觉系统(六 最终篇)
开发语言·python·opencv·计算机视觉
逐花归海.2 小时前
『 C++ 入门到放弃 』- 多态
开发语言·c++·笔记·程序人生
卜锦元2 小时前
Go中使用wire进行统一依赖注入管理
开发语言·后端·golang
军训猫猫头3 小时前
3.检查函数 if (!CheckStart()) return 的妙用 C#例子
开发语言·c#
coding随想3 小时前
JavaScript中的系统对话框:alert、confirm、prompt
开发语言·javascript·prompt
灵哎惹,凌沃敏3 小时前
C语言/Keil的register修饰符
c语言·开发语言