如何在C#9 中使用顶级程序 (top-level)

Peony ·
更新时间:2024-09-20
· 172 次阅读

目录

顶级程序

顶级程序中的方法

顶级程序中的类

顶级程序的原理分析

当我们用 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 后,你将会理解 顶级程序 是多么的短小精悍!

以上就是如何在C#9 中使用顶级程序 (top-level)的详细内容,更多关于C#9 中使用顶级程序 (top-level)的资料请关注软件开发网其它相关文章!



C# 程序 top

需要 登录 后方可回复, 如果你还没有账号请 注册新账号