C# 程序的通用结构

C# 程序由一个或多个文件组成。每个文件均包含若干个命名空间。一个命名空间又包含若干个结构接口枚举委托等类型或其他命名空间。 以下示例是包含所有这些元素的 C# 程序主干:

  1. // A skeleton of a C# program
  2. using System;
  3. // Your program starts here:
  4. Console.WriteLine("Hello world!");
  5. namespace YourNamespace
  6. {
  7. class YourClass {}
  8. struct YourStruct { }
  9. interface IYourInterface {}
  10. delegate int YourDelegate();
  11. enum YourEnum {}
  12. namespace YourNestedNamespace
  13. {
  14. struct YourStruct {}
  15. }
  16. }

上面的示例使用顶级语句作为程序的入口点。 C# 9 中添加了此功能。 在 C# 9 之前,入口点是名为 Main 的静态方法,如以下示例所示:

  1. // A skeleton of a C# program
  2. using System;
  3. namespace YourNamespace
  4. {
  5. class YourClass {}
  6. struct YourStruct {}
  7. interface IYourInterface {}
  8. delegate int YourDelegate();
  9. enum YourEnum {}
  10. namespace YourNestedNamespace
  11. {
  12. struct YourStruct {}
  13. }
  14. class Program
  15. {
  16. static void Main(string[] args)
  17. {
  18. //Your program starts here...
  19. Console.WriteLine("Hello world!");
  20. }
  21. }
  22. }