1. 程式人生 > >C# 反射呼叫私有事件

C# 反射呼叫私有事件

原文: 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


本文會經常更新,請閱讀原文: https://lindexi.gitee.io/lindexi/post/C-%E5%8F%8D%E5%B0%84%E8%B0%83%E7%94%A8%E7%A7%81%E6%9C%89%E4%BA%8B%E4%BB%B6.html ,以避免陳舊錯誤知識的誤導,同時有更好的閱讀體驗。

知識共享許可協議 本作品採用 知識共享署名-非商業性使用-相同方式共享 4.0 國際許可協議 進行許可。歡迎轉載、使用、重新發布,但務必保留文章署名林德熙(包含連結: https://lindexi.gitee.io ),不得用於商業目的,基於本文修改後的作品務必以相同的許可釋出。如有任何疑問,請 與我聯絡