开发者

Rewrite lambda extension method

I've created an extension method that works just like I wanted. I've noticed that somehow the party and property parameters are 'copied' into the lambda expression. This way I do not need to maintain a custom list of editor/party/property associations.

However, I need to reset the ButtonEdit's ButtonClick event. Since thi开发者_C百科s one is anonymous I cannot use the -= opertor either.

So, my question is - how do I rewrite this method so that the delegate can be removed? Or, which other approach can I use to handle a specific event handler with extra parameters (such as party and property)?

private static void SetupAddressButtonClickEvent(this ButtonEdit editor, Party party, string property)
{
    editor.SetAddressDisplayText(party, property);
    editor.ButtonClick += (sender, e) =>
        {
            party.ShowAddressLookupDialog(property);
            editor.SetAddressDisplayText(party, property);
        };
}

Thank you, Stefan


Action<object,EventArgs> myaction = (sender, e) =>
        {
            party.ShowAddressLookupDialog(property);
            editor.SetAddressDisplayText(party, property);
        };

editor.ButtonClick += myaction;
editor.ButtonClick -= myaction;

edit option 2 could be:

class MyEventHandler
{
  ... _property;
  ... _party;
  ... _editor;
  public MyEventHandler(... property, ... party, ... editor)
  {
    _property = property;
    _party = party;
    _editor = editor;
  }

  public void Handler(object sender, EventArgs e)
  {
    _party.ShowAddressLookupDialog(_property);
    _editor.SetAddressDisplayText(_party, _property);
  }
}

and then use it like this:

var handler = new MyEventHandler(party,property,editor);
editor.ButtonClick += handler.Handler;

I'm not sure how much this will help you because I don't 100% understand what you're trying to solve.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜