How do I fix 'compiler error - cannot convert

2019-02-16 13:57发布

问题:

 public MainWindow()
 {
    CommandManager.AddExecutedHandler(this, ExecuteHandler);
 }

 void ExecuteHandler(object sender, ExecutedRoutedEventArgs e)
 {
 }

Error 1 Argument 2: cannot convert from 'method group' to 'System.Delegate'

回答1:

I guess there are multiple ExecuteHandler with different signatures. Just cast your handler to the version you want to have:

CommandManager.AddExecuteHandler(this, (Action<object,ExecutedRoutedEventArgs>)ExecuteHandler);


回答2:

You cannot pass a "method" directly as a parameter, you need to pass an expression. You can either wrap the method into a delegate:

CommandManager.AddExecutedHandler(this, new ExecutedRoutedEventHandler(ExecuteHandler));
CommandManager.AddExecutedHandler(this, (Action<object,ExecutedRoutedEventArgs>) ExecuteHandler);

or into a lambda – which is my personal favorite, since you don't need to memorize a delegate name:

CommandManager.AddExecutedHandler(this, (s, e) => ExecuteHandler(s, e));


标签: c# delegates