问题描述
- 利用反射来判断按钮是否添加了某个事件中的疑问
-
在网上查找资料中时候看到下面的代码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"); }
问题来了:
PropertyInfo pi = btn.GetType().GetProperty("Events", BindingFlags.Instance | BindingFlags.NonPublic);
这一句的意思应该是获取属性名为“Event”的属性的信息,但是找了半天,发现button中没有名称为"Event"的属性啊,求大神指点
解决方案
Events是在Control基类中定义的。Button继承自Control
时间: 2023-12-06 15:14:04