是否可以在C#中获取eventhandler的实例? 就像在C ++中获取函数指针一样
我想要的是获取文本框的事件处理程序,可以在不同的部分和不同的时间设置不同的文本框。
实施例: 对于TextBox,我们有如下代码:
TextBox tbUserName;
tbUserName.Click += new EventHandler( (s, e) => { MessageBox.Show("bla") } );
我希望另一个函数能够获得这样的处理程序:
EventHandler h = tbUserName.Click;
但它不起作用。什么编译器说,点击仅支持+ = - =但不能在右侧。
答案 0 :(得分:0)
该事件实际上是一个多播委托,并且可以使用简单的+ =和 - =语法指定处理程序。
例如......
private void myButton_Click(object sender, EventArgs e)
{
// Do something in here...
}
...
...
myButton.Click += myButton_Click;
答案 1 :(得分:0)
订阅:<event> += <method>
取消订阅:<event> -= <method>
代码显示订阅同一点击事件的三种方法
tbUserName.Click += new EventHandler( (s, e) => { MessageBox.Show("method 1 called") } );
tbUserName.Click += new EventHandler( (s, e) => { MessageBox.Show("method 2 called") } );
tbUserName.Click += new EventHandler( (s, e) => { MessageBox.Show("method 3 called") } );
http://msdn.microsoft.com/en-us/library/17sde2xt(v=VS.100).aspx
答案 2 :(得分:0)
您可以检索事件的调用列表,并且可以从每次调用中检索Target(对于静态eventhandler方法可以为null)和MethodInfo。
这样的事情:
public class TestEventInvocationList {
public static void ShowEventInvocationList() {
var testEventInvocationList = new TestEventInvocationList();
testEventInvocationList.MyEvent += testEventInvocationList.MyInstanceEventHandler;
testEventInvocationList.MyEvent += MyNamedEventHandler;
testEventInvocationList.MyEvent += (s, e) => {
// Lambda expression method
};
testEventInvocationList.DisplayEventInvocationList();
Console.ReadLine();
}
public static void MyNamedEventHandler(object sender, EventArgs e) {
// Static eventhandler
}
public event EventHandler MyEvent;
public void DisplayEventInvocationList() {
if (MyEvent != null) {
foreach (Delegate d in MyEvent.GetInvocationList()) {
Console.WriteLine("Object: {0}, Method: {1}", (d.Target ?? "null").ToString(), d.Method);
}
}
}
public void MyInstanceEventHandler(object sendef, EventArgs e) {
// Instance event handler
}
}
这将产生:
Object: ConsoleApplication2.TestEventInvocationList, Method: Void MyInstanceEven
tHandler(System.Object, System.EventArgs)
Object: null, Method: Void MyNamedEventHandler(System.Object, System.EventArgs)
Object: null, Method: Void <MyMain>b__0(System.Object, System.EventArgs)