简体   繁体   中英

How do I fix 'compiler error - cannot convert from method group to System.Delegate'?

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

 void ExecuteHandler(object sender, ExecutedRoutedEventArgs e)
 {
 }

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

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);

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));

I got this error due to a completely different problem.

        var engine = new Ingest(GetOperationType, GetSqlConnection);

    private static SqlConnection GetSqlConnection(string instanceCode, string defaultDB)
        =>  new SqlConnection($"Server={InstanceMap[instanceCode]};Database={defaultDB};Trusted_Connection=True;");


    private static Type GetOperationType(string operationName)
        => Type.GetType(typeof(BaseOperation).Namespace + "." + operationName + ", ConditioningEngine.EnginePlugins");

Both params to 'new Ingest...' are different types of delegate. The GetOperationType param had no problem while GetSqlConnection got the 'cannot convert from method group' error.
After trying the casting trick mentioned in the other answers the error changed to System.Data.SqlClient not referenced. After fixing the reference problem I could get rid of the cast. That is, the error was false. The casting trick was useful in letting me see what the real error was but the cast itself wasn't necessary. It seems the true error could be almost anything.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM