为什么这个代表没有工作?

时间:2017-02-14 00:20:24

标签: c# .net delegates

在控制台应用中,我有以下内容:

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'

testerMyDelegate具有相同的签名。我做错了什么?

1 个答案:

答案 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
}

你在其他方法中声明静态方法(但我相信它只是复制粘贴错误)。