【发布时间】:2014-10-21 02:10:07
【问题描述】:
我有一个名为Test 的类,它有一个constructor 接受Action<T>,另一个接受Func<T,T>。请看下面的sn-p。
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; }
}
但下面的行会引发一个模棱两可的调用错误
Test<string> t1 = new Test<string>(this.MyMethod1);
Test<string> t2 = new Test<string>(this.MyMethod2);
有趣的是,我有两个方法与我的 Test 类 constructor 的签名相同,它们不会引发任何模棱两可的错误
Test<string> t = new Test<string>();
t.MyMethod1(MyMethod1);
t.MyMethod2(MyMethod2);
谁能帮我确定并解决问题。
【问题讨论】:
-
请澄清:问题是“为什么分配不编译”还是“为什么分配不编译时方法调用编译”?
-
请有金徽章的人将此作为this 的副本关闭。我重新打开以更改建议的重复项,但我不允许这样做:(
标签: c# oop constructor