[英]How Do I Pass A Method Reference to A Different Method in C#
I would like to pass a reference of a method into another method and store it as a variable. 我想将一个方法的引用传递给另一个方法,并将其存储为变量。 Later, I would like to use this reference to define an event handler.
稍后,我想使用此引用来定义事件处理程序。
When making an event handler, a method reference is passed like: 制作事件处理程序时,将像以下那样传递方法引用:
myButton.Click += new RoutedEventHandler(myButton_Click);
And if you look at the constructor for "RoutedEventHandler" from intelliSense, it looks like: 如果您查看intelliSense中“ RoutedEventHandler”的构造函数,则它看起来像:
RoutedEventHandler(void(object, RoutedEventArgs))
What I would like to do is pass the method "myButton_Click" to a different static method and then create an event handler there. 我想做的是将方法“ myButton_Click”传递给另一个静态方法,然后在其中创建一个事件处理程序。 How do I pass the reference to the static method?
如何将引用传递给静态方法? I tried the following but it doesn't compile:
我尝试了以下操作,但无法编译:
public class EventBuilder
{
private static void(object, RoutedEventArgs) _buttonClickHandler;
public static void EventBuilder(void(object, RoutedEventArgs) buttonClickHandler)
{
_buttonClickHandler = buttonClickHandler;
}
public static void EnableClickEvent()
{
myButton.Click += new RoutedEventHandler(_buttonClickHandler);
}
}
Thanks, Ben 谢谢,本
To reference a Method Reference (called a delegate in .NET), use the Handler name, rather than the signature. 若要引用方法引用(在.NET中称为委托 ),请使用处理程序名称而不是签名。
public class EventBuilder
{
private static RoutedEventHandler _buttonClickHandler;
public EventBuilder(RoutedEventHandler buttonClickHandler)
{
_buttonClickHandler = buttonClickHandler;
}
public static void EnableClickEvent()
{
myButton.Click += new RoutedEventHandler(_buttonClickHandler);
}
}
尝试
private static delegate void(object sender, RoutedEventArgs e) _buttonClickHandler;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.