這個問題來自論壇,原文為如何判斷事件已經被注冊過?
用反射取出事件綁定的委托實例,然後用GetInvocationList就可以得到所有注冊的方法了。
代碼
view plaincopy to clipboardprint?
01.using System;
02.using System.Collections.Generic;
03.using System.ComponentModel;
04.using System.Data;
05.using System.Drawing;
06.using System.Text;
07.using System.Windows.Forms;
08.using System.Reflection;
09.namespace WindowsApplication19
10.{
11. public partial class Form1 : Form
12. {
13. public Form1()
14. {
15. InitializeComponent();
16.
17. this.Load+=new EventHandler(Form1_Load1);
18. this.Load+=new EventHandler(Form1_Load2);
19.
20. PropertyInfo propertyInfo = (typeof(Form)).GetProperty("Events", BindingFlags.Instance | BindingFlags.NonPublic);
21. EventHandlerList eventHandlerList = (EventHandlerList)propertyInfo.GetValue(this, null);
22. FieldInfo fieldInfo = (typeof(Form)).GetField("EVENT_LOAD", BindingFlags.Static | BindingFlags.NonPublic);
23.
24. Delegate d = eventHandlerList[fieldInfo.GetValue(null)];
25.
26. if (d != null)
27. {
28. foreach (Delegate de in d.GetInvocationList())
29. Console.WriteLine(de.Method.Name);
30. }
31. }
32. private void Form1_Load1(object sender, EventArgs e)
33. {
34. //什麼也不干
35. }
36. private void Form1_Load2(object sender, EventArgs e)
37. {
38. //什麼也不干
39. }
40. }
41.}