-1

是否可以在 C# 中获取事件处理程序的实例?就像在 C++ 中获取函数指针一样

我想要的是获取文本框的事件处理程序,它可能在不同的部分和不同的时间设置不同。

示例:对于文本框,我们有如下代码:

TextBox tbUserName;
tbUserName.Click += new EventHandler( (s, e) => { MessageBox.Show("bla") } );

我希望另一个函数能够像这样获取处理程序:

EventHandler h = tbUserName.Click;

但它不起作用。编译器说的, Click 只支持 += -= 但不能在右手边。

4

3 回答 3

0

该事件实际上是一个多播委托,并且可以使用简单的 += 和 -= 语法指定处理程序。

例如...

private void myButton_Click(object sender, EventArgs e)
{

   // Do something in here...

}

...
...

myButton.Click += myButton_Click;
于 2012-09-27T10:23:09.397 回答
0
  • 在 C# 中,没有单独的事件处理程序类型,但事件机制建立在 Delegate 类型之上。
  • 委托/多播委托对象类似于 c++ 函数指针,可以存储一个、多个方法地址并可以被调用。
  • C#以关键字事件的形式提供了一个语法糖,一旦源代码被编译,它就变成了一个多播委托。
  • 可以订阅和取消订阅事件

订阅:<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

于 2012-09-27T10:41:06.987 回答
0

您可以检索事件的调用列表,并且可以从每次调用中检索 Target(对于静态事件处理程序方法可以为 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)
于 2012-09-27T10:57:07.677 回答