[英]What are top level statements in C#? What is their use?
I just created my first .NET 6 console app, and instead of the default,我刚刚创建了我的第一个 .NET 6 控制台应用程序,而不是默认的,
using System;
using System.Collections.Generic;
using System.Linq;
namespace MyApp
{
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
I got:我有:
// See https://aka.ms/new-console-template for more information
Console.WriteLine("Hello, World!");
And even when there's no class, the program runs, I took a look at the link provided in the comments.即使没有 class,程序也会运行,我查看了评论中提供的链接。 but I don't know if this is a new feature or an old one, If this is a new feature?
但我不知道这是新功能还是旧功能,如果这是新功能? does that mean C# will be allowing C-style programming hereafter?
这是否意味着 C# 以后将允许 C 风格的编程?
It's a new feature of C# 9 or 10. Microsoft documentation says following:这是 C# 9 或 10 的新功能。Microsoft 文档说明如下:
Top-level statements enable you to avoid the extra ceremony required by placing your program's entry point in a static method in a class.
通过将程序的入口点放在 class 中的 static 方法中,顶级语句使您能够避免所需的额外仪式。 The typical starting point for a new console application looks like the following code:
新控制台应用程序的典型起点类似于以下代码:
using System;
namespace Application
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
The preceding code is the result of running the dotnet new console command and creating a new console application.
上述代码是运行 dotnet new console 命令并创建新控制台应用程序的结果。 Those 11 lines contain only one line of executable code.
这 11 行只包含一行可执行代码。 You can simplify that program with the new top-level statements feature.
您可以使用新的顶级语句功能简化该程序。 That enables you to remove all but two of the lines in this program:
这使您可以删除该程序中除两行之外的所有行:
Console.WriteLine("Hello, World!");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.