您现在的位置是:亿华云 > IT科技

如何在 C#9 中使用程序 (Top-Level)

亿华云2025-10-03 15:44:11【IT科技】6人已围观

简介本文转载自微信公众号「码农读书」,作者码农读书 。转载本文请联系码农读书公众号。当我们用 C# 进行编码的时候,总需要写很多的模板代码,即使是最简单的 console 程序,想象一下,如果去测试一个

本文转载自微信公众号「码农读书」,中使作者码农读书 。用程转载本文请联系码农读书公众号。中使

当我们用 C# 进行编码的用程时候,总需要写很多的中使模板代码,即使是用程最简单的 console 程序,想象一下,如果去测试一个 类库 或者 API 的中使功能,通常你会用 Console 程序去实现,用程在开始工作的中使时候会发现你受到了 C# 标准模板的限制,业务逻辑必须要写在 Main 里,用程如下代码所示:

class Program    {         static void Main(string[] args)        {             //todo        }    } 

顶级程序 是 C#9 中引入的一个新概念,允许你直接写自己的中使业务逻辑而不必受到模板代码的限制,顶级程序 是用程一个非常的特性,可以让代码更加的中使干净,简短和可读,用程你可以通过顶级程序去探索新的中使 idea,这篇文章将会讨论如何在 C#9 中使用顶级程序。香港云服务器

顶级程序

在 C# 9.0 之前,下面的写法在 Console 程序中已经是最小化的了。

using System; namespace IDG_Top_Level_Programs_Demo {      class Program     {          static void Main(string[] args)         {              Console.WriteLine("Hello World!");         }     } } 

在 C# 9.0 时代,可以祭出 顶级程序 来消除那些烦人的模板代码,让代码的逻辑意图更明显,改造后的代码如下:

using System; Console.WriteLine("Hello World!"); 

顶级程序中的方法

你也可以在顶级程序中使用方法,如下例子所示:

System.Console.WriteLine(DisplayMessage("Joydip!")); System.Console.Read(); static string DisplayMessage(string name) {      return "Hello, " + name; } 

程序跑起来后,控制台将会输出:Hello, Joydip!

顶级程序中的类

你也可以在顶级程序中使用类,结构体,枚举,下面的代码展示了如何使用。

System.Console.WriteLine(new Author().DisplayMessage("Joydip!")); System.Console.Read(); public class Author {      public string DisplayMessage(string name)     {          return "Hello, " + name;     } } 

顶级程序的原理分析

现在我们来分析一下,顶级程序的底层逻辑到底是怎么样的,它本质上是一种语法糖,一种编译器的特性,也就是说你没有写模板代码的亿华云时候,编译器会帮你生成,替你负重前行,参考下面的代码段。

using System; Console.WriteLine("Hello World!"); 

然后用在线工具 SharpLab https://sharplab.io/ 看一下编译器替你补齐的代码。

using System; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Security; using System.Security.Permissions; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("0.0.0.0")] [module: UnverifiableCode] [CompilerGenerated] internal static class <Program>$ {      private static void <Main>$(string[] args)     {          Console.WriteLine("Hello World!");     } } 

总的来说,顶级程序 非常适合那些想 快速试错,验证想法 的场景,有一点要特别注意,应用程序中只能仅有一个文件使用 顶级程序,如果存在多个,编译器会抛出错误的,还有一点,如果你是 C# 新手,你可能不理解顶级程序的底层逻辑,更好的方式就是老老实实的使用原生模板代码,当你主宰了 Main 后,你将会理解 顶级程序 是多么的短小精悍!

译文链接:https://www.infoworld.com/article/3612196/how-to-use-top-level-programs-in-csharp-9.html

亿华云计算

很赞哦!(45)

相关文章