C#9.0:Top-Level Programs

我们称之为顶级层序

用 C# 编写一个简单的程序需要大量的样板代码,引用,类、方法、结构体等:

1   class Program
2     {
3         static void Main(string[] args)
4         {
5             Console.WriteLine("Hello World!");
6                         
7         }
8     }

 

这不仅对语言初学者来说是难以承受的,而且还会使代码混乱,增加缩进级别。

在 C# 9.0 中,您可以选择在顶级编写你的主程序(main program):

1 using System;
2 Console.WriteLine("Brand  is a handsome boy!"); 

允许任何语句。此程序必须在文件中的 using 语句之后,任何类型或命名空间声明之前执行,并且只能在一个文件中执行。就像目前只能有一个 Main 方法一样。

如果您想返回一个状态码,您可以做。如果您想等待(await),您可以做。如果您想访问命令行参数,args 可以作为一个“魔法”参数使用。

1 using System;
2 using System.Threading.Tasks;
3 
4 Console.WriteLine(args[0]);
5 await Task.Delay(2000);
6 return 1

局部函数是语句的一种形式,也允许在顶级程序中使用。从顶级语句部分之外的任何地方调用它们都是错误的。

1 using System;
2 using System.Threading.Tasks;
3 
4 Console.WriteLine(hello("Brand"));
5 string hello(string uname)
6 {
7     return "hello " + uname;
8

posted @ 2021-01-30 17:58  Hello-Brand  阅读(225)  评论(0编辑  收藏  举报