2019-11-29-C#-反射调用私有事件

title author date CreateTime categories
C# 反射调用私有事件
lindexi
2019-11-29 08:51:13 +0800
2018-09-19 20:44:19 +0800
C# 反射

在 C# 反射调用私有事件经常会不知道如何写,本文告诉大家如何调用

假设有 A 类的代码定义了一个私有的事件

    class A
    {
        private event EventHandler Fx
        {
            add { }
            remove { }
        }
    }

通过反射可以拿到 A 的事件 Fx 但是无法直接添加事件

            var eventInfo = typeof(A).GetEvent("Fx", BindingFlags.Instance | BindingFlags.NonPublic);

如果这时直接调用 AddEventHandler 就会出现下面异常

            var eventInfo = typeof(A).GetEvent("Fx", BindingFlags.Instance | BindingFlags.NonPublic);

            var a = new A();

            eventInfo.AddEventHandler(a, new EventHandler(Fx));

            void Fx(object sender, EventArgs e)
            {
            }
System.InvalidOperationException:“由于不存在此事件的公共添加方法,因此无法添加该事件处理程序。”

解决的方法是调用 GetAddMethod 的方法请看下面

            var eventInfo = typeof(A).GetEvent("Fx", BindingFlags.Instance | BindingFlags.NonPublic);
            var addFx = eventInfo.GetAddMethod(true);
            var removeFx = eventInfo.GetRemoveMethod(true);

            var a = new A();

            addFx.Invoke(a, new[] {new EventHandler(Fx)});
            removeFx.Invoke(a, new[] {new EventHandler(Fx)});

            void Fx(object sender, EventArgs e)
            {
            }

参见 https://stackoverflow.com/a/6423886/6116637

如果可能遇到类型转换的异常System.ArgumanetException:'Object of type 'System.EventHandler1[System.EventArgs]' cannot be converted to type 'System.EventHandler'. ,请看.NET/C# 使用反射注册事件 - walterlv

更多反射请看

win10 uwp 反射

.NET Core/Framework 创建委托以大幅度提高反射调用的性能 - walterlv

设置 .NET Native 运行时指令以支持反射(尤其适用于 UWP) - walterlv

.NET/C# 使用反射调用含 ref 或 out 参数的方法 - walterlv

.NET/C# 推荐一个我设计的缓存类型(适合缓存反射等耗性能的操作,附用法) - walterlv

posted @ 2019-11-29 16:02  lindexi  阅读(249)  评论(0编辑  收藏  举报