将附加参数传递给 System.Action,C#
好吧,我在库中有一个按钮,如下所示:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
从表面上看,您需要执行以下操作:
然后您可以添加处理程序:
By the look of things you need to do something like this:
And then you can add your handler:
我认为最好使用事件而不是操作,考虑阅读以下一些类似的问题: 事件行动>> 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.