【问题标题】:passing additional parameter to System.Action, C#将附加参数传递给 System.Action,C#
【发布时间】:2011-09-05 12:33:58
【问题描述】:

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

    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
}

但编译器不允许这样做。如何解决这个问题?

谢谢。

【问题讨论】:

  • 如果可能的话,谁来决定id 的值是多少?调用委托的框架代码当然不知道您的id。当然有一种合法的方式可以做你想做的事,但你需要考虑更广泛的范围。
  • 谁将 id 传递给代理?
  • 对不起,我忘了解释。我们有一个额外的数据,那个按钮不知道,比如 int data[];。 button.onClicked 处理程序看起来像 button.onClicked += delegate { System.Console.Write(data[id]); } 该 id 必须从外部委托。
  • 看起来这是将事件公开为 Action 的设计问题,为此目的始终使用标准事件处理程序的signarute,EventArgs 作为第二个参数

标签: c# delegates action


【解决方案1】:

看起来你需要做这样的事情:

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

【讨论】:

  • 谢谢!正是我想要的!
【解决方案2】:

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

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

希望对你有用。

【讨论】:

    猜你喜欢
    • 2011-12-21
    • 2013-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-26
    • 2011-07-10
    • 2015-12-30
    • 2015-03-03
    相关资源
    最近更新 更多