将附加参数传递给System.Action,C#

将附加参数传递给System.Action,C#,c#,delegates,action,C#,Delegates,Action,我在库中有一个按钮,如下所示: public class Button { public event Action<UIButtonX> onClicked; // // when button clicked, on OnClicked method is called // protected virtual void OnClicked () { if (onClicked

我在库中有一个按钮,如下所示:

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

现在我想把参数传递给匿名委托,比如

button.onClicked += delegate(UIButton obj, int id) {
 //do something with id
}
但编译器不允许这样做。如何处理这个问题


谢谢。

从外观上看,您需要执行以下操作:

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);
        }
    }
}

我认为最好用事件而不是行动,考虑一下下面的一些相似的问题: 下面的文章对于理解这两种方法之间的差异非常有帮助:


希望它对您有用。

如果可能的话,谁来决定
id
的值?调用委托的框架代码肯定不知道您的
id
。当然有一种合法的方式来做你想做的事情,但你需要考虑更广泛的范围。谁将id传递给代表?对不起,我忘了解释。我们有一个额外的数据,按钮不知道,比如int data[];。button.onClicked处理程序看起来像button.onClicked+=委托{System.Console.Write(数据[id]);},该id必须从外部传递给委托。看起来这是将事件作为操作公开的设计问题,为此,始终使用标准事件处理程序的Signarate,并将EventArgs作为第二个参数谢谢!正是我想要的!
button.onClicked += delegate(UIButton obj, int id) {
 //do something with id
}
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);
        }
    }
}
button.onClicked += (button, id) => { /* code here */ }