C# 常用命名空間參考指南

筆記一些常用到的命名空間

1. 基礎核心命名空間

1
2
3
4
5
6
7
8
9
10
using System;                     // 基礎類型、例外處理
using System.Collections; // 非泛型集合
using System.Collections.Generic; // 泛型集合
using System.Linq; // LINQ 查詢
using System.ComponentModel; // 資料綁定、型別轉換
using System.Text; // 文字處理
using System.Text.RegularExpressions; // 正則表達式
using System.Globalization; // 地區和文化資訊
using System.Configuration; // 應用程式配置(.NET Core/5+ 需另裝 System.Configuration.ConfigurationManager NuGet 套件;新專案建議改用 Microsoft.Extensions.Configuration)
using System.Runtime.Serialization; // 序列化

2. 檔案與 I/O 處理

1
2
3
4
5
6
7
using System.IO;                 // 檔案與目錄操作
using System.IO.Compression; // 檔案壓縮
using System.IO.Ports; // 序列埠通訊
using System.Xml; // XML 處理
using System.Xml.Linq; // LINQ to XML
using System.Xml.Serialization; // XML 序列化
using System.Xml.Schema; // XML Schema

3. 網路與 Web 開發

1
2
3
4
5
6
7
8
9
10
11
12
13
14
using System.Net;               // 基礎網路功能
using System.Net.Http; // HTTP 客戶端
using System.Net.Mail; // 電子郵件
using System.Net.Sockets; // TCP/IP 網路
using System.Web; // Web 應用程式
using System.Web.Http; // Web API
using System.Web.Mvc; // ASP.NET MVC
using Microsoft.AspNetCore; // .NET Core Web 應用
using Microsoft.AspNetCore.SignalR; // 即時通訊
using Microsoft.AspNetCore.Authentication; // 身份驗證
using Microsoft.AspNetCore.Authorization; // 授權
using Microsoft.Extensions.DependencyInjection; // 依賴注入
using Microsoft.Extensions.Configuration; // 配置
using Microsoft.Extensions.Logging; // 日誌

4. 資料庫存取

1
2
3
4
5
6
7
8
9
using System.Data;              // 資料庫通用功能
using Microsoft.Data.SqlClient; // SQL Server 連線(System.Data.SqlClient 已進入維護模式,新專案請用此套件)
using System.Data.Entity; // Entity Framework
using Microsoft.EntityFrameworkCore; // EF Core
using Dapper; // Dapper ORM
using Microsoft.Data.Sqlite; // SQLite
using Npgsql; // PostgreSQL
using MongoDB.Driver; // MongoDB
using StackExchange.Redis; // Redis

5. 訊息佇列與事件匯流排

1
2
3
4
using RabbitMQ.Client;         // RabbitMQ
using Azure.Messaging.ServiceBus; // Azure Service Bus
using MassTransit; // MassTransit
using Azure.Messaging.EventHubs; // Azure Event Hubs(Microsoft.Azure.EventHubs 為舊版 SDK,已停止新功能開發)

6. 雲端服務整合

1
2
3
4
5
using Azure.Storage.Blobs;     // Azure Blob Storage
using Azure.Identity; // Azure 身份認證
using Amazon.S3; // AWS S3
using Amazon.SQS; // AWS SQS
using Google.Cloud.Storage.V1; // Google Cloud Storage

7. 效能與監控

1
2
3
4
5
using System.Diagnostics;       // 效能監控、事件記錄
using OpenTelemetry; // 分散式追蹤
using OpenTelemetry.Metrics; // 指標收集
using App.Metrics; // 應用程式指標(最後穩定版 4.3.0,2021 年後無更新,新專案建議評估 OpenTelemetry)
using Prometheus; // Prometheus 監控

8. 快取

1
2
3
using Microsoft.Extensions.Caching.Memory;  // 記憶體快取
using Microsoft.Extensions.Caching.StackExchangeRedis; // Redis 快取(舊版 Microsoft.Extensions.Caching.Redis 已棄用)
using LazyCache; // 延遲快取

9. 背景工作

1
2
3
4
5
using Hangfire;               // 背景工作排程
using Quartz; // 工作排程
using Microsoft.Extensions.Hosting; // 託管服務
using System.Reactive; // 反應式程式設計
using System.Reactive.Linq; // Rx.NET

10. 測試相關

1
2
3
4
5
6
using Microsoft.VisualStudio.TestTools.UnitTesting; // MSTest
using Xunit; // xUnit
using NUnit.Framework; // NUnit
using Moq; // Mock 框架
using FluentAssertions; // 流暢的斷言
using AutoFixture; // 測試資料產生

使用情境範例

1. 檔案操作

1
2
3
4
5
6
7
8
using System.IO;
using System.Text;

// 讀取文字檔
string content = File.ReadAllText("file.txt", Encoding.UTF8);

// 寫入檔案
File.WriteAllText("output.txt", "內容", Encoding.UTF8);

2. 資料庫操作

1
2
3
4
5
6
7
8
using Microsoft.Data.SqlClient;

string connectionString = "連線字串";
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
// 執行 SQL 命令
}

3. HTTP 請求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
using System.Net.Http;
using Microsoft.Extensions.DependencyInjection;

// 正確做法:透過 IHttpClientFactory 取得 HttpClient
// 每次 new HttpClient() 再 Dispose 會導致 socket 未立即釋放,高頻呼叫下容易耗盡 port
// 在 Program.cs / Startup 註冊:
// builder.Services.AddHttpClient();

public class MyService
{
private readonly HttpClient _client;

public MyService(IHttpClientFactory factory)
{
_client = factory.CreateClient();
}

public async Task<string> FetchAsync()
{
var response = await _client.GetAsync("https://api.example.com");
return await response.Content.ReadAsStringAsync();
}
}

4. JSON 處理

1
2
3
4
5
6
7
8
using Newtonsoft.Json;

// 序列化
var product = new { Id = 1, Name = "範例" };
string json = JsonConvert.SerializeObject(product);

// 反序列化
var result = JsonConvert.DeserializeObject<Product>(json);

注意:Newtonsoft.Json 為第三方套件,需透過 NuGet 安裝。.NET 5+ 內建 System.Text.Json,新專案可優先考慮。

5. 依賴注入設定

1
2
3
4
5
6
7
8
using Microsoft.Extensions.DependencyInjection;

public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<IUserService, UserService>();
services.AddSingleton<ICacheService, RedisCacheService>();
services.AddTransient<IEmailSender, SmtpEmailSender>();
}

6. 非同步操作與取消

1
2
3
4
5
6
7
8
9
10
using System.Threading;
using System.Threading.Tasks;

public async Task ProcessDataAsync(CancellationToken cancellationToken)
{
await Task.WhenAll(
Task1Async(cancellationToken),
Task2Async(cancellationToken)
);
}

7. 分散式快取

1
2
3
4
5
6
7
using Microsoft.Extensions.Caching.Distributed;

public async Task<string> GetCachedDataAsync(IDistributedCache cache, string key)
{
return await cache.GetStringAsync(key) ??
await FetchAndCacheDataAsync(cache, key);
}

注意事項

  • global using(C# 10+):可在 GlobalUsings.cs 集中宣告常用命名空間,避免每個檔案重複 using
  • 動態載入組件Assembly.Load 等反射操作有執行期成本,避免放在熱路徑。
  • #if 條件編譯:跨框架版本(.NET Framework / .NET 6+)共用程式碼時用 #if NETFRAMEWORK 等符號隔開差異。
  • 已棄用的命名空間System.Web.*(ASP.NET Classic)、System.Data.Entity(EF6)不能在 .NET 5+ 使用;System.Data.SqlClient 已進入維護模式,改用 Microsoft.Data.SqlClient
  • 第三方套件版本:定期檢查 NuGet 套件是否有安全更新,尤其是序列化(Newtonsoft.Json)與 ORM(Dapper、EF Core)。