# 多播委托(Multicast Delegates)

// 定义委托
public delegate void MyDelegate(string message);
// 方法 A
public static void MethodA(string message)
{
    Console.WriteLine($"Method A: {message}");
}
// 方法 B
public static void MethodB(string message)
{
    Console.WriteLine($"Method B: {message}");
}
static void Main()
{
    MyDelegate combinedDelegate = new MyDelegate(MethodA);
    combinedDelegate += MethodB;
    combinedDelegate.Invoke("Hello, World!");
    // 输出:Method A: Hello, World!
    // Method B: Hello, World!
    combinedDelegate -= MethodB;
    combinedDelegate.Invoke("Hello, World!");
    // 输出:Method A: Hello, World!
    Console.ReadKey();
}

# 例如还可以复杂一点

// 定义委托
public delegate void SayHello(string userName);
// 英文方法
private static void EnglishSay(string userName)
{
    Console.WriteLine("Hello!" + userName);
}
// 中文方法
private static void ChineseSay(string userName)
{
    Console.WriteLine("你好!" + userName);
}
// 将委托当参数传入另一个方法
private static void Say(string userName, SayHello say)
{
    say(userName);
}
static void Main()
{
    Say("小明", EnglishSay);
    Say("小明", ChineseSay);
    Console.ReadKey();
}

# 匿名方法

// 定义委托
public delegate void AnonymousDelegate(int number);
static void Main()
{
    AnonymousDelegate anonymous = delegate (int num)
    {
        Console.WriteLine($"Square of {num}: {num * num}");
    };
    anonymous(5); // 输出:Square of 5: 25
    Console.ReadKey();
}

# Action 用法

static void Main()
{
    Action<string> lambda = message => Console.WriteLine($"From Lambda: {message}");
    lambda("Hello from a lambda!"); // 输出:From Lambda: Hello from a lambda!
    Console.ReadKey();
}

# 当然 Action 也可以传方法

// 定义一个方法给 Action
private static void GetString(string name)
{
    Console.WriteLine(name);
}
static void Main()
{
    // Action 有参无返回值(需定义方法并调用)
    Action<string> stringAction = new Action<string>(GetString);
    stringAction("小明");
    // Action 有参无返回值(匿名方法直接调用)
    Action<string> string2Action = new Action<string>(ac =>
    {
        Console.WriteLine(ac);//ac 等于调用传参的小萌
    });
    string2Action("小萌");
}

# Func 用法

static void Main()
{
    Func<int, string> squareAndFormat = num => $"The square of {num} is {num * num}";
    string result = squareAndFormat(7);
    Console.WriteLine(result);// 输出:The square of 7 is 49
    Console.ReadKey();
}

# 同样 Func 也可以传方法

// 定义一个方法给 Func
public static bool IsNull(string text)
{
    return string.IsNullOrEmpty(text) || string.IsNullOrWhiteSpace(text);
}
static void Main()
{
    // Func 有参有返回值(需定义方法并调用)
    Func<string, bool> isNullFunc = new Func<string, bool>(IsNull);
    Console.WriteLine(isNullFunc(""));
    // Func 有参有返回值(匿名方法直接调用)
    Func<string, bool> isNull2Func = new Func<string, bool>(ac =>
    {
        return string.IsNullOrEmpty(ac) || string.IsNullOrWhiteSpace(ac);//ac 等于调用传参的空字符串
    });
    Console.WriteLine(isNull2Func(""));
    Console.ReadKey();
}

# 异步委托调用(BeginInvoke/EndInvoke)

// 定义委托
public delegate int LongRunningTaskDelegate();
static void Main()
{
    // 休眠两秒返回固定值
    LongRunningTaskDelegate task = () =>
    {
        Thread.Sleep(2000);
        return 66;
    };
    Console.WriteLine("开始");
    //IAsyncResult result = task.BeginInvoke(null, null);
    var waroTask = Task.Run(()=> task.Invoke());
    // 在这里执行其他任务...
    Console.WriteLine("在这里执行其他任务");
    //int returnValue = task.EndInvoke(result);
    int returnValue = waroTask.Result;
    Console.WriteLine($"Task returned: {returnValue}");
    Console.ReadKey();
}

# 注释的代码会出现错误:System.PlatformNotSupportedException:“Operation is not supported on this platform.”

# 详细请看这里:迁移 .NET Core 的 Delegate.BeginInvoke 调用

# 事件(Event)

// 定义事件和委托
public class StringEventArgs : EventArgs
{
    public string Message { get; }
    public StringEventArgs(string message)
    {
        Message = message;
    }
}
public delegate void MessageEventHandler(object sender, StringEventArgs e);
// 引发事件
public class EventPublisher
{
    // 定义事件
    public event MessageEventHandler MessageReceived;
    protected virtual void OnMessageReceived(StringEventArgs e)
    {
        MessageReceived?.Invoke(this, e);
    }
    public void SendMessage(string message)
    {
        var args = new StringEventArgs(message);
        OnMessageReceived(args);
    }
}
// 订阅和取消订阅事件
public class EventSubscriber
{
    public void Subscribe(EventPublisher publisher)
    {
        publisher.MessageReceived += OnMessageReceived;
    }
    public void Unsubscribe(EventPublisher publisher)
    {
        publisher.MessageReceived -= OnMessageReceived;
    }
    private void OnMessageReceived(object sender, StringEventArgs e)
    {
        Console.WriteLine($"Subscriber received message: {e.Message}");
    }
}
// 调用
static void Main()
{
    var publisher = new EventPublisher();
    var subscriber = new EventSubscriber();
    subscriber.Subscribe(publisher);
    publisher.SendMessage("Hello, world!");
    subscriber.Unsubscribe(publisher);
    publisher.SendMessage("Hello, world!");
    Console.ReadKey();
}

# 这里调用了两次 SendMessage,但是只有第一次会触发 OnMessageReceived,第二次不会触发。

更新于 阅读次数

请我喝茶~( ̄▽ ̄)~*

Tianci 微信支付

微信支付

Tianci 支付宝

支付宝