Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/290.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 为什么';这个代表不工作吗?_C#_.net_Delegates - Fatal编程技术网

C# 为什么';这个代表不工作吗?

C# 为什么';这个代表不工作吗?,c#,.net,delegates,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

在控制台应用程序中,我有以下功能:

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
行中,我得到以下错误:

无法从“字符串”转换为“MyDelegate”


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

您没有传递委托-您传递的是
tester(“刚刚测试”)
方法执行的结果(即字符串):

如果要传递委托,请执行以下操作:

t.TestDelegate(tester);
另外,在
TestDelegate
方法中不使用传递的委托
m
。您可以执行以下操作:

public string TestDelegate(MyDelegate m)
{
   return m("success!"); // m will be your tester method and you call it with success param
}

您正在另一个方法中声明静态方法(但我相信这只是复制粘贴打字错误)。

TestDelegate()方法需要一个
MyDelegate
的实例。您正在传递一个
字符串
。如果要传递引用
tester
的委托实例,则只需传递
tester
,即
var newString=t.TestDelegate(tester)。如果那不是你想要的,那么我不知道你想要什么。请修正你的问题,让它有意义。一个普通信封里有多少封信?一个。“普通信封”里有多少封信?十八岁。产生字符串的函数和它产生的字符串是两种截然不同的东西。
public string TestDelegate(MyDelegate m)
{
   return m("success!"); // m will be your tester method and you call it with success param
}