我想将方法的引用传递给另一个方法并将其存储为变量.稍后,我想使用此引用来定义事件处理程序.
在创建事件处理程序时,会传递方法引用,如:
myButton.Click += new RoutedEventHandler(myButton_Click);
如果你从intelliSense查看"RoutedEventHandler"的构造函数,它看起来像:
RoutedEventHandler(void(object, RoutedEventArgs))
我想做的是将方法"myButton_Click"传递给另一个静态方法,然后在那里创建一个事件处理程序.如何将引用传递给静态方法?我尝试了以下但它不编译:
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); } }
谢谢,本
要引用方法引用(在.NET中称为委托),请使用Handler名称而不是签名.
public class EventBuilder { private static RoutedEventHandler _buttonClickHandler; public EventBuilder(RoutedEventHandler buttonClickHandler) { _buttonClickHandler = buttonClickHandler; } public static void EnableClickEvent() { myButton.Click += new RoutedEventHandler(_buttonClickHandler); } }