在哪里可以使用顶级语句在.NET 6控制台模板中定义委托?

发布于 2025-02-04 16:05:43 字数 316 浏览 4 评论 0原文

我最近尝试了带有顶级语句的.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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

醉南桥 2025-02-11 16:05:43

问题在于,代表声明必须在顶级语句之后进行。代表声明不算为顶级语句,而是算作类型声明。以下代码正常:

var s = "myString";
Console.WriteLine(s);

delegate string StringReturner(int i);

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:

var s = "myString";
Console.WriteLine(s);

delegate string StringReturner(int i);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文