【问题标题】:.Net cannot get private method by reflection.Net 无法通过反射获取私有方法
【发布时间】:2012-04-02 16:30:52
【问题描述】:

我在使用反射获取私有方法时遇到问题。 即使使用 BindingFlags.NonPublic 和 BindingFlags.Instance 它也不起作用。 HandleClientDrivenStatePropertyChanged 定义在与 CreateRadioPropertyInstances 方法相同的类中。

 class Program
 {
      static void Main(string[] args)
      {
         RadioPropertiesState state = new RadioPropertiesState();
      }
 }

 internal class RadioPropertiesState : BaseRadioPropertiesState
 {
 }

 internal class BaseRadioPropertiesState
 {
     public BaseRadioPropertiesState()
     {
          CreateRadioPropertyInstances();
     }

     private void CreateRadioPropertyInstances()
     {
          // get the method that is subscribed to the changed event
          MethodInfo changedEventHandlerInfo = GetType().GetMethod(
               "HandleClientDrivenStatePropertyChanged",
               BindingFlags.NonPublic | BindingFlags.Instance | 
               BindingFlags.IgnoreCase);
     }

     private void HandleClientDrivenStatePropertyChanged
         (object sender, EventArgs e)
     {
     }
}

GetMethod 返回空值。 可能是什么问题?

[编辑代码]

【问题讨论】:

  • 奇怪,在 .NET 4 上运行良好。尝试使用 BindingFlags
  • 另一个猜测是可能是缺少某些权限造成的。你如何调用使用class X?它是加载到不同域还是从远程源加载,类似 smt?
  • 请展示一个简短但完整的程序来说明问题。应该没问题 - 当然,如果这个方法最终在派生类上被调用,它不会找到它......
  • @Jon Skeet:我发布了更多代码来演示它
  • @leozilla:对我来说,这看起来不像一个完整的程序。 Main 方法在哪里?

标签: .net reflection private-methods


【解决方案1】:

问题与我在评论中建议的完全一样 - 您正在尝试根据对象的 执行时间类型 找到方法,即 RadioPropertiesState... 但它不是以该类型声明或对其可见。

将您的 GetMethod 呼叫更改为:

MethodInfo changedEventHandlerInfo = typeof(BaseRadioPropertiesState)
                                         .GetMethod(...)

而且效果很好。

【讨论】:

    【解决方案2】:

    要获取私有成员,您需要在声明它的确切类型上调用GetMethod,而不是派生类型。

    BindingFlags.FlattenHierarchy 在这里不起作用,因为该方法是私有的。

    【讨论】:

      猜你喜欢
      • 2012-01-23
      • 2022-11-27
      • 1970-01-01
      • 2013-08-15
      • 2010-12-21
      • 2012-07-14
      • 1970-01-01
      • 2020-08-04
      • 1970-01-01
      相关资源
      最近更新 更多