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

发布于 2024-12-03 12:16:42 字数 720 浏览 0 评论 0原文

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

    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{
  //do something
}

button.onClicked += HandleButtonClick;

void HandleButtonClick(UIButton obj){
}

现在我想将参数传递给匿名委托,

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

但编译器不允许这样做。怎么处理这个问题呢?

谢谢。

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

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

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

冬天的雪花 2024-12-10 12:16:42

从表面上看,您需要执行以下操作:

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 */ }

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 */ }
小情绪 2024-12-10 12:16:42

我认为最好使用事件而不是操作,考虑阅读以下一些类似的问题: 事件行动>> vs event EventHandler<>C# Action/Delegate 风格问题

以及下面的文章对于理解这种方法之间的差异非常有帮助:
http://blog.monstuff.com/archives/000040.html

希望可以对你有用。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文