我有一个场景,我想使用方法组语法而不是匿名方法(或lambda语法)来调用函数.
该函数有两个重载,一个需要一个Action,另一个需要一个Func<string>.
我可以愉快地使用匿名方法(或lambda语法)调用两个重载,但如果我使用方法组语法,则会获得Ambiguous调用的编译器错误.我可以明确的解决方法铸造到Action或Func<string>,但不认为这应该是必要的.
任何人都可以解释为什么应该要求显式演员表.
代码示例如下.
class Program
{
static void Main(string[] args)
{
ClassWithSimpleMethods classWithSimpleMethods = new ClassWithSimpleMethods();
ClassWithDelegateMethods classWithDelegateMethods = new ClassWithDelegateMethods();
// These both compile (lambda syntax)
classWithDelegateMethods.Method(() => classWithSimpleMethods.GetString());
classWithDelegateMethods.Method(() => classWithSimpleMethods.DoNothing());
// These also compile (method group with explicit cast)
classWithDelegateMethods.Method((Func<string>)classWithSimpleMethods.GetString);
classWithDelegateMethods.Method((Action)classWithSimpleMethods.DoNothing);
// These both error with "Ambiguous invocation" (method group)
classWithDelegateMethods.Method(classWithSimpleMethods.GetString);
classWithDelegateMethods.Method(classWithSimpleMethods.DoNothing);
}
}
class ClassWithDelegateMethods
{
public void Method(Func<string> func) { /* do something …Run Code Online (Sandbox Code Playgroud) 我有一个叫做接受的课Test,另一个接受.请参阅以下代码段.constructorAction<T>Func<T,T>
public class Test<T>
{
//constructors
public Test() { }
public Test(Action<T> action) { }
public Test(Func<T, T> action) { }
//methods with same signature of constructor
public void MyMethod1(Action<T> action) { }
public void MyMethod2(Func<T, T> action) { }
}
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Test<string> t1 = new Test<string>(this.MyMethod1);
Test<string> t2 = new Test<string>(this.MyMethod2);
Test<string> t = new Test<string>();
t.MyMethod1(MyMethod1);
t.MyMethod2(MyMethod2);
}
public void MyMethod1(string value) { …Run Code Online (Sandbox Code Playgroud)