日期:2014-05-18  浏览次数:21565 次

c# 中如何获取事件的委托链
如题:我现在想获得如Button的Click事件的委托链,即有哪些代理加在事件代理上。我用
((EventHandler)fpSpreadOrder.Change).GetInvocationList();但是不行,
错误为错误:
事件“FarPoint.Win.Spread.FpSpread.Change”只能出现在 += 或 -= 的左边。
不知道有什么办法获得事件的委托链。
注明:不是在自定义控件等事件。而是事件定义外。

------解决方案--------------------
这个意思?

 private void button1_Click(object sender, EventArgs e)
{
Delegate[] _List = GetObjectEventList(button1, "EventClick", typeof(Control));
}



public static Delegate[] GetObjectEventList(object p_Object, string p_EventName, Type p_EventType)
{
PropertyInfo _PropertyInfo = p_Object.GetType().GetProperty("Events", BindingFlags.Instance | BindingFlags.NonPublic);
if (_PropertyInfo != null)
{
object _EventList = _PropertyInfo.GetValue(p_Object, null);
if (_EventList != null && _EventList is EventHandlerList)
{
EventHandlerList _List = (EventHandlerList)_EventList;
FieldInfo _FieldInfo = p_EventType.GetField(p_EventName, BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.IgnoreCase);
if (_FieldInfo == null) return null;
Delegate _ObjectDelegate = _List[_FieldInfo.GetValue(p_Object)];
if (_ObjectDelegate == null) return null;
return _ObjectDelegate.GetInvocationList();
}
}
return null;
}
------解决方案--------------------
C# code

       static void Main(string[] args)
        {
            System.Windows.Forms.Button btn = new System.Windows.Forms.Button();
            btn.Click += new EventHandler(btn_Click);
            btn.Click += new EventHandler(btn_Click2);
            btn.Click += new EventHandler(btn_Click3);
            PropertyInfo pi = btn.GetType().GetProperty("Events", BindingFlags.Instance | BindingFlags.NonPublic);
            EventHandlerList ehl = (EventHandlerList)pi.GetValue(btn, null);
            FieldInfo fieldInfo = (typeof(System.Windows.Forms.Control)).GetField("EventClick", BindingFlags.Static | BindingFlags.NonPublic);
            Delegate d = ehl[fieldInfo.GetValue(null)];
            foreach (Delegate del in d.GetInvocationList())
                Console.WriteLine(del.Method.Name);
        }

        static void btn_Click(object sender, EventArgs e)
        {
            Console.WriteLine("Click1");
        }

        static void btn_Click2(object sender, EventArgs e)
        {
            Console.WriteLine("Click2");
        }

        static void btn_Click3(object sender, EventArgs e)
        {
            Console.WriteLine("Click3");
        }

------解决方案--------------------
之前我做的时候是用reflector知道的。
反射只要指定BindingFlags.NonPublic就是获取非公有成员