理解 C# 程式結構是組織、建置、部署應用程式的基礎。本文詳細說明命名空間、類別、Main 入口點、陳述式/運算式、編譯執行流程、專案檔結構、現代 .NET 專案範本。
// 1. using 指令:引入命名空間型別
using System;
using System.Collections.Generic;
// 2. 命名空間:邏輯分組,防止名稱衝突
namespace MyApp {
// 3. 類別:資料與行為封裝
public class Program {
// 4. Main 方法:程式進入點
public static void Main(string[] args) {
// 5. 陳述式與運算式
Console.WriteLine("Hello, World!");
var message = "Hello"; // 運算式
Console.WriteLine(message); // 陳述式
}
}
}
.NET 6+ 專案範本預設:
// Program.cs - 完整程式
using System;
using System.Linq;
var names = new[] { "Alice", "Bob", "Charlie" };
var greeting = $"Hello, {string.Join(", ", names)}!";
Console.WriteLine(greeting);
編譯器自動產生 Program 類別與 Main 方法。適用於腳本、控制台應用、最小 API。
namespace MyApp; // 整個檔案
public class Service { }
| 簽章 | 用途 | 版本 |
|---|---|---|
static void Main() | 基本 | 1.0+ |
static int Main() | 回傳結束代碼 | 1.0+ |
static void Main(string[] args) | 命令列參數 | 1.0+ |
static int Main(string[] args) | 參數 + 結束代碼 | 1.0+ |
static async Task Main() | 非同步 | 7.1+ |
static async Task | 非同步 + 參數 + 代碼 | 7.1+ |
參數:args[0] 為第一個參數 (非程式名稱)。Windows 檔案關聯啟動時參數包含檔案路徑。
| 類別 | 說明 | 範例 |
|---|---|---|
| 宣告陳述式 | 宣告變數/常數 | int x = 1; |
| 運算式陳述式 | 運算式後加分號 | x++;, Method(); |
| 選擇陳述式 | if, switch | if (x>0) {} |
| 迭代陳述式 | for, foreach, while, do-while | for (int i=0; i<10; i++) {} |
| 跳躍陳述式 | break, continue, return, throw, goto | return x; |
| try 陳述式 | try-catch-finally | try {} catch {} |
| checked/unchecked | 溢位檢查內容 | checked { x = y * z; } |
| lock/using | 資源管理 | using (var f = File.Open(...)) {} |
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings> <!-- 自動引入常用命名空間 -->
<Nullable>enable</Nullable> <!-- 可為 Null 參考型別 -->
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
</ItemGroup>
</Project>
| 範本 | OutputType | 用途 |
|---|---|---|
| console | Exe | 控制台應用 |
| classlib | Library | 類別庫 (DLL) |
| webapi | Exe | ASP.NET Core Web API |
| mvc | Exe | ASP.NET Core MVC |
| blazor | Exe | Blazor WebAssembly/Server |
| xunit/nunit/mstest | Library | 單元測試專案 |
| worker | Exe | 背景服務 |
MySolution/
├── src/
│ ├── MyApp/ # 主控制台專案
│ │ ├── Program.cs
│ │ ├── Services/
│ │ └── MyApp.csproj
│ ├── MyApp.Core/ # 核心領域邏輯 (ClassLib)
│ └── MyApp.Infrastructure/ # 基礎設施實作 (ClassLib)
├── tests/
│ ├── MyApp.UnitTests/
│ └── MyApp.IntegrationTests/
├── MySolution.sln
├── Directory.Build.props # 共用建置屬性
└── nuget.config # NuGet 來源設定
bin/
├── Debug/
│ └── net8.0/
│ ├── MyApp.dll # 組件
│ ├── MyApp.pdb # 偵錯符號
│ ├── MyApp.deps.json # 相依性圖
│ ├── MyApp.runtimeconfig.json # 執行期設定
│ └── ref/ # 參考組件 (僅公開 API)
└── Release/...
| 模式 | 特點 | 適用 |
|---|---|---|
| Framework-dependent | 需目標機安裝 .NET Runtime | 伺服器、開發機、容器基底映像含 Runtime |
| Self-contained | 包含 Runtime,單一執行檔 | 無法安裝 Runtime 環境、邊緣裝置、單一檔案部署 |
| Single-file | 發布為單一 .exe | 簡化部署、啟動稍慢 (解壓縮) |
| AOT (NativeAOT) | 編譯為原生碼,無 JIT | 啟動極快、體積小、無動態載入 |
Company.Product.Module:Acme.Sales.OrderingDomain, Application, Infrastructure, PresentationMyApp.Abstractions vs MyApp.SqlServerusing,專案層級管理全域引入。A: 不可以。一個專案只能有一個檔案包含最上層陳述式 (預設 Program.cs)。其他檔案需用傳統結構。
A: 專案檔 <StartupObject>MyApp.Program</StartupObject> 或編譯器 /main:MyApp.Program。
A: 可以 (設定 OutputType>Exe</OutputType),但慣例類別庫為 Library,測試/主控台專案參考它。
ref 組件?A: bin/Debug/net8.0/ref/MyApp.dll 僅包含公開 API 中繼資料,供編譯時參考,加速建置、避免循環參考。