转: http://www.cnblogs.com/lovecherry/archive/2005/06/13/173668.html
我们在做应用程序的时候有时候想知道页面上的按钮对于某一事件委托链上有多少方法,下面是一个例子。
1、先添加3个按钮,分别添加0个,1个,2个click事件的方法,按钮名字分别为button1,button2,button3。
this
.button2.Click
+=
new
System.EventHandler(
this
.button2_Click);
this .button3.Click += new System.EventHandler( this .button3_Click1);
this .button3.Click += new System.EventHandler( this .button3_Click2);
this .button3.Click += new System.EventHandler( this .button3_Click1);
this .button3.Click += new System.EventHandler( this .button3_Click2);
2、方法里面可以随便写点代码:
private
void
button2_Click(
object
sender, System.EventArgs e)
{
MessageBox.Show( " button2_Click " );
}
private void button3_Click1( object sender, System.EventArgs e)
{
MessageBox.Show( " button3_Click1 " );
}
private void button3_Click2( object sender, System.EventArgs e)
{
MessageBox.Show( " button3_Click2 " );
}
{
MessageBox.Show( " button2_Click " );
}
private void button3_Click1( object sender, System.EventArgs e)
{
MessageBox.Show( " button3_Click1 " );
}
private void button3_Click2( object sender, System.EventArgs e)
{
MessageBox.Show( " button3_Click2 " );
}
3、再放一个textbox(textbox1)用来填写按钮的名字,一个listbox(listbox1)显示按钮的click事件处理方法,最后放置一个按钮,点击这个按钮显示textbox1填写的那个按钮的click事件的处理方法于listbox1上,代码如下:
if
(
this
.textBox1.Text
==
""
)
MessageBox.Show( " 填写一个按钮的id " );
else
{
Button btn = null ;
foreach (Control c in this .Controls)
if (c.Name == this .textBox1.Text)
btn = (Button)c;
this .listBox1.Items.Clear();
PropertyInfo pi = ( typeof (Button)).GetProperty( " Events " ,BindingFlags.Instance | BindingFlags.NonPublic);
EventHandlerList ehl = (EventHandlerList)pi.GetValue(btn, null );
FieldInfo fi = ( typeof (Control)).GetField( " EventClick " ,BindingFlags.Static | BindingFlags.NonPublic);
Delegate d = ehl[fi.GetValue( null )];
if (d != null )
{
foreach (Delegate de in d.GetInvocationList())
this .listBox1.Items.Add(de.Method.Name);
}
else
{
this .listBox1.Items.Add( " 没有任何处理方法 " );
}
}
MessageBox.Show( " 填写一个按钮的id " );
else
{
Button btn = null ;
foreach (Control c in this .Controls)
if (c.Name == this .textBox1.Text)
btn = (Button)c;
this .listBox1.Items.Clear();
PropertyInfo pi = ( typeof (Button)).GetProperty( " Events " ,BindingFlags.Instance | BindingFlags.NonPublic);
EventHandlerList ehl = (EventHandlerList)pi.GetValue(btn, null );
FieldInfo fi = ( typeof (Control)).GetField( " EventClick " ,BindingFlags.Static | BindingFlags.NonPublic);
Delegate d = ehl[fi.GetValue( null )];
if (d != null )
{
foreach (Delegate de in d.GetInvocationList())
this .listBox1.Items.Add(de.Method.Name);
}
else
{
this .listBox1.Items.Add( " 没有任何处理方法 " );
}
}
别忘记
using
System.Reflection;
为何如此复杂?是因为这些控件的事件都封装到了EventHandlerList内,而它不是公共成员,因此还需要通过反射来剥离出来。