开发者

C# attach event handling with additional parameters

PREFACE

I have a Windows form Button that exposes the event OnClick (object sender, EventArgs e). In my application I can handle this by using the classic event handling technique of C#:

// Button Creation
Button button = new Button();
button.Click += MyEventHandler;

Then Windows Form ask me for an handler with the following signature:

public void MyEventHandler(object sender, EventArgs e) { }

Suppose that I would like to use lambda expression to do this I can use the syntax:

button.Click += (sender, args) =>
{
  // execute the code
};

The drawback of this is that I can't unsubscribe from a Lambda expression.

QUESTIO开发者_开发问答N

What I would like to do is to have an utility class that will allow me to handle any Click event plus using an additional Action as a parameter. So I would like to write something like this:

button.Click += MyUtility.Click(() 
    => {
        // the custom code the Click event will execute
    })

Can I do it in somehow?


You can assign the lambda expression to a local variable or field.

For example:

EventHandler handler = (sender, args) =>
{
  // execute the code
};

button.Click += handler;
button.Click -= handler;

If you want to unsubscribe inside the handler, you'll need to assign handler to null, then to the lambda, to avoid definite assignment issues.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜