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
}