重庆市公共资源交易中心网站,备份wordpress数据库,国内目前比较好的crm系统,齐河专业企业网站建设当我们用 C# 进行编码的时候#xff0c;总需要写很多的模板代码#xff0c;即使是最简单的 console 程序,想象一下#xff0c;如果去测试一个 类库 或者 API 的功能#xff0c;通常你会用 Console 程序去实现#xff0c;在开始工作的时候会发现你受到了 C# 标准模板的限制… 当我们用 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