程序结构与编译

翻译整理自 C# 程序结构 与 Compilation stages。

1. 经典 Main 入口

C# 9 之前必须写:

using System;

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

2. 顶级语句(C# 9+)

using System;

Console.WriteLine("Hello");

一个项目只能有一个文件使用顶级语句。其本质是 Main 方法的语法糖。

带参数与返回:

foreach (var arg in args)
    Console.WriteLine(arg);

return 0;

3. 命名空间

namespace MyApp.Services
{
    class UserService { }
}

// 文件作用域命名空间(C# 10)
namespace MyApp.Services;

class UserService { }

// global using(C# 10+)
global using System;
global using System.Linq;

4. using 指令

using System;                         // 引入命名空间
using System.Text;                    // 可省略 using
using static System.Math;             // 静态成员引入
using别名 = System.Console;            // 别名
using Project = MyCompany.Project;     // 别名命名空间

C# 10+ 可在 .csproj 中开启全局:

<ImplicitUsings>enable</ImplicitUsings>

会自动 global using 常用命名空间。

5. 项目文件

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
    <LangVersion>latest</LangVersion>
    <AssemblyName>myapp</AssemblyName>
    <RootNamespace>MyApp</RootNamespace>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
  </ItemGroup>

  <ItemGroup>
    <ProjectReference Include="..\MyLib\MyLib.csproj" />
  </ItemGroup>

</Project>

6. 编译过程

  1. C# 源码 → Roslyn 编译器
  2. 程序集 Assembly(.dll/.exe)含 CIL 中间语言与元数据
  3. JIT 编译:CLR 运行时把 CIL 编译为本地机器码
  4. AOT 编译(.NET 7+ Native AOT):直接生成本地可执行
# 默认 JIT
dotnet build
dotnet run

# Native AOT
dotnet publish -r win-x64 -p:PublishAot=true

7. 程序集 Assembly

  • 包含 IL 代码、元数据、清单
  • 强命名:可签名 dotnet build -p:SignAssembly=true
  • 版本控制:[assembly: AssemblyVersion("1.0.0.0")]

8. 多目标

可同时支持多个框架:

<TargetFrameworks>net8.0;net6.0;net48</TargetFrameworks>

条件编译:

#if NET8_0
    // .NET 8
#elif NET48
    // .NET Framework 4.8
#endif

小结

了解命名空间、顶级语句、项目文件后,你已经可以构建可运行的 C# 程序。