我在使用反射获取私有方法时遇到问题。 即使使用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返回null。 可能是什么问题?
[编辑代码]
答案 0 :(得分:3)
问题与我在评论中建议的完全一样 - 您正在尝试根据对象的执行时间类型找到方法,即RadioPropertiesState
...但是它没有在该类型中声明或对其可见。
将您的GetMethod
电话改为:
MethodInfo changedEventHandlerInfo = typeof(BaseRadioPropertiesState)
.GetMethod(...)
它工作正常。
答案 1 :(得分:0)
要获取私有成员,您需要在声明它的确切类型上调用GetMethod
,而不是派生类型。
BindingFlags.FlattenHierarchy
在这里不起作用,因为该方法是私有的。