为什么 .NET Core 5 中的 Program.cs 中没有任何 Class?
Why Doesn't have any Class in Program.cs in .NET Core 5?
我正在尝试使用 .NET 5 来更新我的信息。所以我开始审查 eShopOnContainers-ServicesAndWebApps 项目 here.
我读过它的旧版本(2.2 和 3.1),这是一个丰富的样本,有很多精彩之处。但是 here 在 .NET 5 中,乍一看,在 Program.cs
中,我看到很多方法和属性没有任何 classes,我无法理解并让我感到困惑。我们如何在 cs 文件中使用没有 class 的方法?
这是 C# 9 的一个特性:top-level statements
Top-level statements remove unnecessary ceremony from many applications.
Only one file in your application may use top-level statements. If the compiler finds top-level statements in multiple source files, it’s an error. It’s also an error if you combine top-level statements with a declared program entry point method, typically a Main method. In a sense, you can think that one file contains the statements that would normally be in the Main method of a Program class.
所以你现在可以编写一个只包含这行代码的程序:
System.Console.WriteLine("Hello World!");
我正在尝试使用 .NET 5 来更新我的信息。所以我开始审查 eShopOnContainers-ServicesAndWebApps 项目 here.
我读过它的旧版本(2.2 和 3.1),这是一个丰富的样本,有很多精彩之处。但是 here 在 .NET 5 中,乍一看,在 Program.cs
中,我看到很多方法和属性没有任何 classes,我无法理解并让我感到困惑。我们如何在 cs 文件中使用没有 class 的方法?
这是 C# 9 的一个特性:top-level statements
Top-level statements remove unnecessary ceremony from many applications.
Only one file in your application may use top-level statements. If the compiler finds top-level statements in multiple source files, it’s an error. It’s also an error if you combine top-level statements with a declared program entry point method, typically a Main method. In a sense, you can think that one file contains the statements that would normally be in the Main method of a Program class.
所以你现在可以编写一个只包含这行代码的程序:
System.Console.WriteLine("Hello World!");