C# 委托:方法名称预期错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2309708/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Delegate: Method name expected error
提问by pistacchio
I'm trying to get the following simple Delegate example working. According to a book I've taken it from it should be ok, but I get a Method name expected
error.
我正在尝试使以下简单的委托示例工作。根据我从它那里拿走的一本书应该没问题,但我得到了一个Method name expected
错误。
namespace TestConsoleApp
{
class Program
{
private delegate string D();
static void Main(string[] args)
{
int x = 1;
D code = new D(x.ToString());
}
}
}
Any help?
有什么帮助吗?
采纳答案by Hans Ke?ing
Remove the ():
去除那个 ():
D code = new D(x.ToString);
You want to specifythe method, not executeit.
您想指定方法,而不是执行它。
回答by cjk
Try taking the brackets off the end of the method, you are passing the method, hence don't need to use the brackets.
尝试从方法的末尾去掉括号,您正在传递方法,因此不需要使用括号。
回答by Fitzchak Yitzchaki
D code = new D(x.ToString); // Note the: ()
D code = new D(x.ToString); // Note the: ()
You need to pas the method to be executed in the delegate. What that you're doing is passing the value instead of the signature of the function.
您需要传递要在委托中执行的方法。您正在做的是传递值而不是函数的签名。
回答by Jon Skeet
I think you mean:
我想你的意思是:
D code = new D(x.ToString);
Note the lack of brackets. With the brackets on, it was a method invocation- i.e. you were trying to execute x.ToString()
in that line of code. Without the brackets, it's a method group- an expression which tells the compiler to look at the available methods with that name (in that context), precisely for the purpose of creating delegates.
请注意缺少括号。使用方括号,它是一个方法调用- 即您试图x.ToString()
在该行代码中执行。没有括号,它是一个方法组- 一个表达式,它告诉编译器查看具有该名称的可用方法(在该上下文中),正是为了创建委托。
Which book are you using? If it really has the brackets in the examples it shows, you may want to email the author (or at least check the book's errata page). If it's C# in Depth, I'll go and cry in a corner...
你用的是哪本书?如果它显示的示例中确实有括号,您可能需要给作者发电子邮件(或至少检查本书的勘误页)。如果是C# in Depth,我就去角落哭……
回答by Darin Dimitrov
Should be:
应该:
D code = new D(x.ToString);
回答by Jens
You need to feed a method into the delegate constructor.
您需要将一个方法提供给委托构造函数。
x.ToString()
is not a method, but a string. Use
不是一个方法,而是一个字符串。用
D code = new D(x.ToString);