FieldInfo在Component上返回null

时间:2014-12-02 04:25:01

标签: c# winforms

我正在尝试获取BindingSource的事件列表,并返回null作为我的代码:

// bs is my BindingSource
PropertyInfo propertyInfo = bs.GetType()
    .GetProperty("Events", BindingFlags.NonPublic | BindingFlags.Static | 
        BindingFlags.Instance | BindingFlags.FlattenHierarchy);

EventHandlerList eventHandlerList = propertyInfo
    .GetValue(bs, new object[] { }) as EventHandlerList;

// The following line returns null
FieldInfo fieldInfo = typeof(BindingSource)
    .GetField("AddingNew", BindingFlags.Instance | BindingFlags.FlattenHierarchy | 
        BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); 

我放了所有可能的BindingFlags,但错误仍然存​​在。 我做错了什么?

1 个答案:

答案 0 :(得分:0)

找到更好的答案,因为重复AddEventHandler using reflection - 使用Type.GetEvent


AddingNew是事件,因此要操纵它,您需要获取相应的自动生成方法 - “remove_ {EventName}”和“add_ {EventName}”:

var add = typeof(System.Windows.Forms.BindingSource).GetMethod("add_AddingNew");

正确使用GetEvent

var adding = typeof(System.Windows.Forms.BindingSource).GetEvent("AddingNew");

有关如何实施事件的详情,请参阅How are events implemented