在哪里可以使用顶级语句在.NET 6控制台模板中定义委托?
我最近尝试了带有顶级语句的.NET 6控制台模板,并在Visual Studio中偶然发现了A gotcha 。如果您尝试编译以下代码,Visual Studio将在字符串声明下给出一条红色的线条var s =“ mystring”;
。您还将收到错误:顶级语句必须先于名称空间并键入声明。
delegate string StringReturner(int i);
var s = "myString";
Console.WriteLine(s);
因此,这里有什么问题?
I recently tried the .Net 6 console template, with top level statements, in Visual studio and stumbled into a Gotcha. If you try to compile the below code, Visual Studio will give a red squiggly line under the string declaration var s = "myString";
. You will also receive the error: Top-level statements must precede namespace and type declarations.
delegate string StringReturner(int i);
var s = "myString";
Console.WriteLine(s);
So, what is the problem here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题在于,代表声明必须在顶级语句之后进行。代表声明不算为顶级语句,而是算作类型声明。以下代码正常:
The issue is that the delegate declaration has to happen after the top level statements. A delegate declaration does not count as a top level statement, but counts as a type declaration. The following code works fine: