开发者

passing additional parameter to System.Action, C#

Well, I have a button in library that looks like following:

    public cla开发者_StackOverflowss Button  {
       public event Action<UIButtonX> onClicked;
       //
       // when button clicked, on OnClicked method is called
       //
       protected virtual void OnClicked () {
            if (onClicked != null) onClicked (this);
       }
    }

When i want to handle button click, i'm writing something like:

button.onClicked += delegate{
  //do something
}

or

button.onClicked += HandleButtonClick;

void HandleButtonClick(UIButton obj){
}

Now I want to pass parameter to anonymous delegate, like

button.onClicked += delegate(UIButton obj, int id) {
 //do something with id
}

but compiler doesn't allow this. How to deal that problem?

Thanks.


By the look of things you need to do something like this:

public class Button
{
    public event Action<UIButtonX, int> onClicked;

    public int Id { get; set; }

    protected virtual void OnClicked ()
    {
        var e = this.onClicked;
        if (e != null)
        {
            e(this, this.Id);
        }
    }
}

And then you can add your handler:

button.onClicked += (button, id) => { /* code here */ }


I think it is better to use events instead of actions, consider reading some of the following similar qustions: event Action<> vs event EventHandler<> and C# Action/Delegate Style Question

And folowing article is quite helpful for understanding differences between this approaches: http://blog.monstuff.com/archives/000040.html

Hope it would be useful to you.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜