C# 程序结构
命名空间、类、Main 方法、顶级语句,以及一个文件的最小骨架。
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| Part | Meaning |
|---|---|
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#
0The 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.传统结构
C#
using System;
namespace MyApp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("参数个数:" + args.Length);
}
}
}Output
$ dotnet run -- a b
参数个数:2| 部分 | 含义 |
|---|---|
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编译器会把顶级语句塞进一个隐式生成的 Main 里。一个项目只能有一个文件用顶级语句,其他文件正常写类。教学和脚本场景用它最省事。
多个类与方法
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;namespace Shop; 后面所有类型都属于它,不用再包一层大括号。项目里通常把常用 global using 集中写在一个 GlobalUsings.cs 里。
Main 的合法签名有四种:void Main()、void Main(string[] args)、int Main()、int Main(string[] args)。返回 int 就是进程退出码。还可以写成 async Task Main。