C# 9.0 Top-level statements

概述

Top-level statements开始于C#9.0,你不需要在一个console应用程序里显示声明Main方法,大大减少代码量。

原代码:
using System;

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

现代码:
using System;

Console.WriteLine("Hello World!");

使用条件

1、一个程序有且仅有一个入口,故Top-level statements也应该只有一个。
    CS8802 Only one compilation unit can have top-level statements.
2、声明了顶级语句之后,可以显示声明个Main方法,但是该Main方法不能作为程序的入口,否则会报错。
    CS7022 The entry point of the program is global code; ignoring 'Main()' entry point.
3、一个文件中可以有顶级语句、namespace和类型定义,但是顶级语句必须在最前面。
    MyClass.TestMethod();
    MyNamespace.MyClass.MyMethod();

    public class MyClass
    {
        public static void TestMethod()
        {
            Console.WriteLine("Hello World!");
        }

    }

    namespace MyNamespace
    {
        class MyClass
        {
            public static void MyMethod()
            {
                Console.WriteLine("Hello World from MyNamespace.MyClass.MyMethod!");
            }
        }
    }

对比

Top-level code contains Implicit Main signature
await and return static async Task<int> Main(string[] args)
await static async Task Main(string[] args)
return static int Main(string[] args)
No await or return static void Main(string[] args)
原文地址:https://www.cnblogs.com/az4215/p/15352544.html