1.顶级语句原理
从 C# 9 开始,无需在应用程序项目中显式包含 Main
方法。
顶级语句的原理是把Program类中Main方法内的内容抽取出来放到文件的顶层,是一种隐式的入口点方式,顶级语句隐式位于全局命名空间中。具体顺序见下面:
//语句顺序
using 语句;
顶级语句;
类(必须位于顶级语句之后);
命名空间(必须位于顶级语句之后);
//C# 9.0(包含)之后
// A skeleton of a C# program
using System;
// Your program starts here:
Console.WriteLine("Hello world!");
namespace YourNamespace
{
class YourClass
{
}
struct YourStruct
{
}
interface IYourInterface
{
}
delegate int YourDelegate();
enum YourEnum
{
}
namespace YourNestedNamespace
{
struct YourStruct
{
}
}
}
//C# 9.0(不包含)之前
// A skeleton of a C# program
using System;
namespace YourNamespace
{
class YourClass
{
}
struct YourStruct
{
}
interface IYourInterface
{
}
delegate int YourDelegate();
enum YourEnum
{
}
namespace YourNestedNamespace
{
struct YourStruct
{
}
}
class Program
{
static void Main(string[] args)
{
//Your program starts here...
Console.WriteLine("Hello world!");
}
}
}
一般情况下,一个项目只能有一个包含Main
方法入口点的文件,因此一个项目也只能有一个包含顶级语句的文件。
可以显式编写 Main
方法,但它不能作为入口点。编译器将发出以下警告:CS7022:程序的入口点是全局代码;忽略“Main()”入口点。
2.编译器
编译器将为顶级语句生成类 和 入口点方法,为了方便起见,在此使用方法名称 Main
,所以也支持类和Main
方法同等的内容。
2.1args参数
if (args.Length > 0)
{
foreach (var arg in args)
{
Console.WriteLine($"Argument={arg}");
}
}
else
{
Console.WriteLine("No arguments");
}
2.2隐式入口点方法签名
顶级代码包含 | 隐式 Main 签名 |
---|---|
await 和 return | static async Task<int> Main(string[] args) |
await | static async Task Main(string[] args) |
return | static int Main(string[] args) |
无 await 或 return | static void Main(string[] args) |
原创文章,作者:huoxiaoqiang,如若转载,请注明出处:https://www.huoxiaoqiang.com/experience/csharpe/15212.html