Ambiguity with Action and Func parameter

前端 未结 3 1326
旧时难觅i
旧时难觅i 2021-02-12 19:10

How is it possible that this code

TaskManager.RunSynchronously(fileMananager.BackupItems, package);

causes a compile error

3条回答
  •  余生分开走
    2021-02-12 20:12

    The reason is that the return type of a method is not part of its signature. Thus, while resolving the correct overload, the compiler only looks at the parameter of the method.

    The easiest solution is to simply not use the implicit method group conversion. All of the following compile:

    TaskManager.RunSynchronously(
        x => fileMananager.BackupItems(x), package);
    
    TaskManager.RunSynchronously(
        (Action)fileMananager.BackupItems, package);
    
    TaskManager.RunSynchronously(
        new Action(fileMananager.BackupItems), package);
    

    The first one is the most elegant of them, but it also is the only one with a - slight - runtime performance impact, because of an additional redirection. However, this impact is so small that you actually shouldn't care.

提交回复
热议问题