简体   繁体   English

C#如何使用EventHandler?

[英]C# How to use the EventHandler?

I'm just creating a ContextMenu.. 我正在创建一个ContextMenu。

At this line, I don't know what I shall put in the third param (or better: how I have to form it -syntaxly-): 在这一行,我不知道我将在第三个参数中放置什么(或者更好:我必须-syntaxly-形成它):

(contextMenuStrip.Items[0] as System.Windows.Forms.ToolStripMenuItem).DropDownItems.Add(contextUnterMenuStrip.Items.Add(exe),null, HERE);

on 'HERE' I have to set an EventHandler onClick 在“这里”,我必须设置一个EventHandler onClick

By Example I got this Method: 通过示例,我得到了以下方法:

public void DoSomething()
{
//...
}

How could I call this Method? 我怎么称呼这个方法? (Over the Eventhandler?) or do I have to make a Method like: (通过Eventhandler?)还是我必须像下面这样创建一个方法:

private void button_Click(object sender, RoutedEventArgs e)
{
    //...
}

Don't "call" the method but take its address. 不要“调用”该方法,而要获取其地址。 Which means omitting the () 这意味着省略()

private void menuItem1_Click(object sender, EventArgs e)
{
    //...
}


// your code, I think it misses a few ')'
... (contextMenuStrip.Items[0] as System.Windows.Forms.ToolStripMenuItem)
       .DropDownItems.Add(contextUnterMenuStrip.Items
       .Add(exe),null, menuItem1_Click);

As you can see here , the callback has to have the following prototype: 如您在此处看到的 ,回调必须具有以下原型:

public delegate void EventHandler( Object sender, EventArgs e )

So your method DoSomething has to look like: 因此,您的方法DoSomething必须看起来像:

private void DoSomething(object sender, EventArgs e)
{
    //...
}

You can create an anonymous event handler using the Linq libraries and call your method that way. 您可以使用Linq库创建匿名事件处理程序,然后以这种方式调用您的方法。 This can be a nice and quick way of doing something (especially if it's just a test project). 这是做某事的好方法(尤其是只是一个测试项目时)。 But if you start using it extensively, it might become difficult to read it. 但是,如果您开始广泛使用它,可能很难阅读它。

An example of this would be: 例如:

var menuItem1 = new MenuItem();
menuItem1.Click += (sender, e) => DoSomething();

Refer here for further information on using Linq: http://msdn.microsoft.com/library/bb308959.aspx 有关使用Linq的更多信息,请参见此处: http : //msdn.microsoft.com/library/bb308959.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM