C# 程序结构

命名空间、类、Main 方法、顶级语句,以及一个文件的最小骨架。

Beginner
Key PointsC# 9 起可以只写语句不写 `Main` —— 编译器自动生成入口。

传统结构

C#
using System;

namespace MyApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("参数个数:" + args.Length);
        }
    }
}
Output
$ dotnet run -- a b
参数个数:2
PartMeaning
using导入命名空间
namespace逻辑分组,避免类名冲突
class类型定义
static void Main程序入口

顶级语句

C#
// Program.cs —— 不需要 class 和 Main
Console.WriteLine("Hello");

var name = "C#";
Console.WriteLine($"你好,{name}");

// 顶级语句里可以直接用 args
Console.WriteLine(args.Length);
Output
Hello
你好,C#
0

The compiler wraps top-level statements in a generated Main. Only one file per project may use them; other files declare classes normally. Ideal for teaching and scripts.

多个类与方法

C#
using System;

namespace Shop
{
    class Product
    {
        public string Name = "";
        public decimal Price;
    }

    class Program
    {
        static void Main()
        {
            var p = new Product { Name = "键盘", Price = 199m };
            Console.WriteLine($"{p.Name} ¥{p.Price}");
        }
    }
}
Output
键盘 ¥199

命名空间的新写法

C#
// 文件范围命名空间(C# 10+),省一层缩进
namespace Shop;

class Product
{
    public string Name = "";
}

// 全局 using(C# 10+):整个项目都生效
global using System.Text;

With namespace Shop; every following type belongs to it — no brace block. Projects usually put common global using lines in a single GlobalUsings.cs.

Main has four valid signatures: void Main(), void Main(string[] args), int Main(), int Main(string[] args). Returning int sets the exit code. async Task Main also works.

Friends & Partners