当前位置: 首页 > 科技观察

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

时间:2023-03-16 01:47:09 科技观察

本文转载自微信公众号《码农读书》,作者码农读书。转载本文请联系码农阅读公众号。我们在使用C#写代码的时候,总是需要写很多模板代码,哪怕是最简单的控制台程序,想象一下,如果你想测试一个类库或者API的功能,通常你会使用Console程序来实现,在开始工作的时候,你会发现受限于C#标准模板,业务逻辑必须写在Main中,如下代码所示:classProgram{staticvoidMain(string[]args){//todo}}顶层程序是在C#9中引入的一个新概念,可以让你不受模板代码的限制,直接编写自己的业务逻辑。顶层程序是一个非常特殊的特性,可以使代码更加简洁、简短和可读。您可以使用顶层程序来探索新思路,本文将讨论如何在C#9中使用顶层程序。顶层程序在C#9.0之前,Console程序中已经最小化了如下写法。usingSystem;namespaceIDG_Top_Level_Programs_Demo{classProgram{staticvoidMain(string[]args){Console.WriteLine("HelloWorld!");}}}在C#9.0时代,顶层程序可以牺牲掉那些烦人的模板代码,让代码的逻辑意图更明显的是,修改后的代码如下:usingSystem;Console.WriteLine("HelloWorld!");顶层程序中的方法您也可以使用顶层程序中的方法,如下例所示:System.Console.WriteLine(DisplayMessage("Joydip!"));System.Console.Read();staticstringDisplayMessage(stringname){return"Hello,"+name;}程序运行后,控制台会输出:Hello,Joydip!您可以在顶级程序中使用类、结构和枚举。下面的代码展示了如何使用它们。System.Console.WriteLine(newAuthor().DisplayMessage("Joydip!"));系统.Console.Read();publicclassAuthor{publicstringDisplayMessage(stringname){return"Hello,"+name;}}顶层程序原理分析下面我们来分析一下顶层程序的底层逻辑是怎样的。它本质上是一个语法糖,是编译器的一个特性。也就是说,当你不写模板代码的时候,编译器会帮你生成。要为您负重,请参阅下面的代码片段。usingSystem;Console.WriteLine("HelloWorld!");然后使用在线工具SharpLabhttps://sharplab.io/查看编译器为你完成的代码。usingSystem;usingSystem.Diagnostics;usingSystem.Reflection;usingSystem.Runtime.CompilerServices;usingSystem.Security;usingSystem.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.[module:UnverifiableCode][CompilerGenerated]internalstaticclass${privatestaticvoid

$(string[]args){Console.WriteLine("HelloWorld!");}}一般来说,顶层程序很适合那些想快速试错,验证想法的人,要特别注意一点,应用程序中只有一个文件可以使用顶级程序,如果有更多比一个文件,编译器会报错,还有一点,如果你是C#新手,你可能不了解顶层程序的底层逻辑。更好的方法是老老实实地使用原生模板代码。当你驾驭了Main,你就会明白顶层程序有多短!翻译链接连接:https://www.infoworld.com/article/3612196/how-to-use-top-level-programs-in-csharp-9.html