使用 C# 反射訪問私有方法
反射提供了一種與私有方法動態交互的強大方法。 但是,標準 GetMethod()
函數本身無法訪問私有成員。 使用 BindingFlags
枚舉可以克服此限制。
解決方案:
要檢索私有方法,請修改您的 GetMethod()
調用以包含必要的 BindingFlags
。 此示例展示瞭如何:
<code class="language-csharp">MethodInfo dynMethod = this.GetType().GetMethod("Draw_" + itemType, BindingFlags.NonPublic | BindingFlags.Instance);</code>
這裡,BindingFlags.NonPublic
確保私有方法包含在搜索中,BindingFlags.Instance
指定我們正在尋找實例方法(而不是靜態方法)。 有了這些標誌,GetMethod()
將成功找到私有方法。
隨後,使用返回的 Invoke()
對像上的 MethodInfo
方法調用私有方法,並提供必要的參數。
以上是C#中如何使用反射動態呼叫私有方法?的詳細內容。更多資訊請關注PHP中文網其他相關文章!