在控制台应用中,我有以下内容:
static void Main(string[] args)
{
var t = New Test();
var newString = t.TestDelegate(tester("just testing"));
public static string tester(string s) {
return s;
}
}
public delegate string MyDelegate(string s);
public class Test
{
public string TestDelegate(MyDelegate m)
{
return "success!";
}
}
这不起作用。在var newString
行,我收到以下错误:
无法转换为' string'到了MyDelegate'
tester
与MyDelegate
具有相同的签名。我做错了什么?
答案 0 :(得分:4)
您没有传递委托 - 您正在传递tester("just testing")
方法执行的结果(字符串):
t.TestDelegate(tester("just testing"))
如果你想传递委托:
t.TestDelegate(tester);
此外,您不会在m
方法中使用传递的委托TestDelegate
。你可以这样做:
public string TestDelegate(MyDelegate m)
{
return m("success!"); // m will be your tester method and you call it with success param
}
你在其他方法中声明静态方法(但我相信它只是复制粘贴错误)。