C# 如何获取事件已经注册了哪些方法

在C#中,可以使用 GetInvocationList() 方法来获取事件已经注册了哪些方法。该方法返回一个Delegate类型的数组,包含了所有已注册的方法。

下面是一个示例代码:

cs 复制代码
using System;

class Program
{
    static void Main(string[] args)
    {
        MyEventClass myEventClass = new MyEventClass();
        myEventClass.MyEvent += Method1;
        myEventClass.MyEvent += Method2;
        // 事件"MyEventClass.MyEvent"只能出现在 += 或 -= 的左边(从类型"MyEventClass"中使用时除外)
        Delegate[] eventHandlers = myEventClass.MyEvent.GetInvocationList();
        // 所以,只能在声明事件的类里定义一个函数来获取
        Delegate[] eventHandlers = myEventClass.GetEventDelegates();
        foreach (Delegate handler in eventHandlers)
        {
            Console.WriteLine(handler.Method.Name);
        }
    }

    static void Method1()
    {
        Console.WriteLine("Method1");
    }

    static void Method2()
    {
        Console.WriteLine("Method2");
    }
}

class MyEventClass
{
    public event Action MyEvent;
    public Delegate[] GetEventDelegates()
    {
       return MyEvent.GetInvocationList();
    }
}

输出结果为:

Method1

Method2

在上面的示例中,MyEventClass类定义了一个MyEvent事件,类型为Action。在Main方法中,我们将Method1Method2方法注册到了MyEvent事件中。然后,我们使用GetInvocationList()方法获取已注册的方法,并逐个打印出它们的名称。

相关推荐
hez20104 天前
在 .NET 上构建超大托管数组
c#·.net·.net core·gc·clr
雨落倾城夏未凉9 天前
第四章c#方法-参数数组和可选参数(16)
后端·c#
唐青枫10 天前
线程不是越多越快:C#.NET Thread 生命周期、同步与后台工作线程实战
c#·.net
唐青枫11 天前
别只会反射:C#.NET Emit 动态生成代码实战详解
c#·.net
咕白m62512 天前
.NET 环境下 Word 超链接批量提取方案
c#·.net
用户917215619021112 天前
C# 通信协议增量解析:用状态机处理半包和粘包
c#
小码编匠12 天前
C# 工控上位机必备:数据转换工具类与十个核心模块
后端·c#·.net
唐青枫14 天前
别再乱用 StartNew:C#.NET TaskFactory 任务调度实战详解
c#·.net
Artech15 天前
[MAF预定义的AIContextProvider-03]ChatHistoryMemoryProvider——赋予Agent从经验中学习的能力
ai·c#·agent·memory·maf
Scout-leaf16 天前
C#摸鱼实录——IoC与DI案例详解
c#