小编KBa*_*Bar的帖子

抛出 NullReferenceException 但对象通过了 null 检查,这怎么可能?

我正在使用该答案中的AddEventHandler方法,但是当在具有值类型参数的EventHandler上执行此操作时,会发生:

using System.Reflection;

public class Program
{
    public static event EventHandler<bool> MyEvent;

    public static void Main()
    {
        EventInfo eventInfo = typeof(Program).GetEvent(nameof(MyEvent));
        AddEventHandler(eventInfo, null, (s, e) => {
            if (e == null) return; // either if condition or null conditional operator
            Console.WriteLine(e?.ToString());
        });
        MyEvent(null, true);
    }

    public static void AddEventHandler(EventInfo eventInfo, object client, EventHandler handler)
    {
        object eventInfoHandler = eventInfo.EventHandlerType
            .GetConstructor(new[] { typeof(object), typeof(IntPtr) })
            .Invoke(new[] { handler.Target, handler.Method.MethodHandle.GetFunctionPointer() });

        eventInfo.AddEventHandler(client, (Delegate)eventInfoHandler);
    }
}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

有什么解释吗?

c# delegates system.reflection eventhandler .net-6.0

2
推荐指数
1
解决办法
251
查看次数