使用+ =运算符将方法绑定到C#中的事件 [英] Binding a Method to an Event in C# with += operator

查看:69
本文介绍了使用+ =运算符将方法绑定到C#中的事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作Windows窗体,并且试图将方法手动绑定到myButton的click事件,如下所示:

I was making a windows form, and I was trying to manually bind a method to the click event of myButton, like this:

    public Form1()
    {
        InitializeComponent();
        myButton.Click = new EventHandler(ShowMessage("You clicked my button!"));
    }

    private void ShowMessage(string message)
    {
        MessageBox.Show(message);
    }

您可能已经猜到了,编译器并不喜欢这样.我不确定为什么,因为我习惯于使用Javascript这样的事情:

As some of you might guess, the compiler didn't like this. I wasn't sure why, because I am used to being able to do things in Javascript like this:

document.getElementById("myButton").onclick = function(){showMessage("You clicked my button")};
function showMessage(message) {
  alert(message);
}

我迷惑了整个过程,最终做了一件非常丑陋的事,涉及到如下这样的全局变量:

I muddled through it and eventually ended up doing something really ugly involving a global variable like this:

    string message = "";
    public Form1()
    {
        InitializeComponent();
        message = "You clicked my button!";
        myButton.Click += ShowMessage; 
    }

    private void ShowMessage(object sender, EventArgs e)
    {
        MessageBox.Show(message);
    }

这是我的两个问题:首先,有没有一种更清洁的方法?其次,为什么必须为事件方法分配一个 + = 而不只是一个 = ?

Here are my two questions: first, is there a cleaner way to do this? Second, why do event methods have to be assigned with a += and not just an =?

推荐答案

必须将事件处理程序添加到带有 + = 的事件中,因为该事件可能还有您的特定代码未知的多个其他委托.纯分配意味着可以删除其他关联的委托人,而作为活动的客户端,您不应具有此权限.

Event handlers must be added to events with += because the event may have multiple other delegates unknown to your particular piece of code. Pure assignment would imply an ability to remove other associated delegates, something you should not have permission to do as a client of the event.

此外,您可能想利用匿名委托来完成任何形式的参数绑定.例如:

Additionally, you probably want to take advantage of anonymous delegates to accomplish any form of argument binding. For example:

myButton.Click += delegate(object sender, EventArgs e) {
    MessageBox.Show("You clicked my button!");
};

这篇关于使用+ =运算符将方法绑定到C#中的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆