Vim*_* CK 13 c# oop constructor
我有一个叫做接受的课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) { }
public string MyMethod2(string value) { return string.Empty; }
}
Run Code Online (Sandbox Code Playgroud)
但是下面的行会引发一个模糊的调用错误
Test<string> t1 = new Test<string>(this.MyMethod1);
Test<string> t2 = new Test<string>(this.MyMethod2);
Run Code Online (Sandbox Code Playgroud)
有趣的是,我有两个方法,我的Test班级具有相同的签名constructor,不会引起任何模棱两可的错误
Test<string> t = new Test<string>();
t.MyMethod1(MyMethod1);
t.MyMethod2(MyMethod2);
Run Code Online (Sandbox Code Playgroud)
有谁可以帮我识别并解决问题.
事实
方法/构造函数重载可以通过参数类型识别正确的方法,但不包括返回类型。
原因
由于在问题中提到的两个构造函数调用中,参数都是 MethodGroup 类型,因此编译器无法确定正确的重载。其次,对该方法的调用是成功的,因为在非重载情况下。
解决
以下是解决该问题的可能选项
将方法调用包装成匿名方法调用并让隐式转换来区分自己。
Test<string> t1 = new Test<string>(s => this.MyMethod1(s));
Test<string> t2 = new Test<string>(s => { return this.MyMethod2(s); });
Run Code Online (Sandbox Code Playgroud)
结果

替代方法
另一种选择是显式转换方法组
Test<string> t1 = new Test<string>((Action<string>)this.MyMethod1);
Test<string> t2 = new Test<string>((Func<string, string>)this.MyMethod2);
Run Code Online (Sandbox Code Playgroud)
如果参数较少,这比第一种方法要长一些