Community程式設計與開發github.com

現代 C# 編碼標準

使用 record、模式比對、值物件、async/await、Span<T>/Memory<T> 及最佳實踐 API 設計模式,撰寫現代、高效能的 C# 程式碼。強調使用 C# 12+ 功能的函數式程式設計風格。

現代 C# 編碼標準 是什麼?

這個技能定義了現代 C# 開發的全面編碼標準,專注於高效能、型別安全及 C# 12+ 功能。它強調不可變性(record 類型)、模式比對、值物件(readonly record struct)、async/await 最佳實踐、Span<T>/Memory<T> 零配置模式,以及透過 Result<T, TError> 進行明確錯誤處理,而非傳統例外。支援平台包含所有 .NET 專案(SDK 風格 csproj),涵蓋主控台應用程式、ASP.NET Core 服務及程式庫。該技能透過提供可遵循的具體程式碼範例、反模式指南及涵蓋語言功能、效能、組合與 API 設計的參考檔案來運作。其目標是透過提倡組合、避免反射式程式碼產生(AutoMapper、Mapster)並確保所有非同步方法皆接受 CancellationToken,來強制執行紀律嚴謹、可維護且高效能的程式碼基底。

相容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/Aaronontheweb/dotnet-skills/tree/main/skills/csharp-coding-standards

Installed? Explore more 程式設計與開發 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

現代 C# 編碼標準 是做什麼的?

使用時機

在以下情況使用此技能:

  • 撰寫新的 C# 程式碼或重構現有程式碼
  • 為函式庫或服務設計公開 API
  • 最佳化對效能要求嚴格的程式碼路徑
  • 使用強型別實作領域模型
  • 建構 async/await 密集型應用程式
  • 處理二進位資料、緩衝區或高吞吐量情境

參考檔案

核心原則

  1. 預設不可變性 - 使用 record 型和 init - only 屬性
  2. 型別安全 - 利用可為 Null 的參考型別和值物件
  3. 現代模式比對 - 廣泛使用 switch 表達式和模式
  4. 非同步隨處 - 偏好使用具備適當取消支援的非同步 API
  5. 零配置模式 - 對效能關鍵程式碼使用 Span<T> 和 Memory<T>
  6. API 設計 - 接受抽象類型,回傳適當特定的類型
  7. 組合優於繼承 - 避免抽象基底類別,偏好組合
  8. 值物件作為結構 - 對值物件使用 readonly record struct

語言模式

用於不可變資料的 Record (C# 9+)

對 DTO、訊息、事件和領域實體使用 record 型別。

// 簡單的不可變 DTO
public record CustomerDto(string Id, string Name, string Email);

// 在建構子中進行驗證的 Record
public record EmailAddress
{
    public string Value { get; init; }

    public EmailAddress(string value)
    {
        if (string.IsNullOrWhiteSpace(value) || !value.Contains('@'))
            throw new ArgumentException("電子郵件地址無效", nameof(value));

        Value = value;
    }
}

// 包含集合的 Record - 使用 IReadOnlyList
public record ShoppingCart(
    string CartId,
    string CustomerId,
    IReadOnlyList<CartItem> Items
)
{
    public decimal Total => Items.Sum(item => item.Price * item.Quantity);
}

何時使用 record class vs record struct:

  • record class(預設):參考型別,用於實體、聚合、具有多個屬性的 DTO
  • record struct:實值型別,用於值物件(請參閱下一節)

值物件作為 readonly record struct

值物件應該總是 readonly record struct,以獲得效能和值語意。使用明確轉換,絕不使用隱含運算子。

public readonly record struct OrderId(string Value)
{
    public OrderId(string value) : this(
        !string.IsNullOrWhiteSpace(value)
            ? value
            : throw new ArgumentException("OrderId 不可為空", nameof(value)))
    { }
    public override string ToString() => Value;
}

public readonly record struct Money(decimal Amount, string Currency);
public readonly record struct CustomerId(Guid Value)
{
    public static CustomerId New() => new(Guid.NewGuid());
}

請參閱 value-objects-and-patterns.md 以取得包含多值物件、工廠模式和無隱含轉換規則的完整範例。

模式比對 (C# 8-12)

使用 switch 表達式、屬性模式、關係模式和清單模式來撰寫更簡潔的程式碼。

public decimal CalculateDiscount(Order order) => order switch
{
    { Total: > 1000m } => order.Total * 0.15m,
    { Total: > 500m } => order.Total * 0.10m,
    { Total: > 100m } => order.Total * 0.05m,
    _ => 0m
};

請參閱 value-objects-and-patterns.md 以取得完整的模式比對範例。


可為 Null 的參考型別 (C# 8+)

在您的專案中啟用可為 Null 的參考型別,並明確處理 Null。

// 在 .csproj 中
<PropertyGroup>
    <Nullable>enable</Nullable>
</PropertyGroup>

// 明確的可為 Null 性
public string? FindUserName(string userId)
{
    var user = _repository.Find(userId);
    return user?.Name;
}

// 使用 Null 檢查的模式比對
public decimal GetDiscount(Customer? customer) => customer switch
{
    null => 0m,
    { IsVip: true } => 0.20m,
    { OrderCount: > 10 } => 0.10m,
    _ => 0.05m
};

// 使用 ArgumentNullException.ThrowIfNull 的守衛子句 (C# 11+)
public void ProcessOrder(Order? order)
{
    ArgumentNullException.ThrowIfNull(order);
    // order 在此範圍中現在為不可為 Null
    Console.WriteLine(order.Id);
}

組合優於繼承

避免抽象基底類別。 使用介面 + 組合。對共享邏輯使用靜態輔助方法。對不同變體使用具有工廠方法的 record。

請參閱 composition-and-error-handling.md 以取得完整範例。


效能模式

Async/Await 最佳實踐

// 完全非同步 - 總是接受 CancellationToken
public async Task<Order> GetOrderAsync(string orderId, CancellationToken cancellationToken)
{
    var order = await _repository.GetAsync(orderId, cancellationToken);
    return order;
}

// 對於頻繁呼叫且通常同步的方法使用 ValueTask
public ValueTask<Order?> GetCachedOrderAsync(string orderId, CancellationToken cancellationToken)
{
    if (_cache.TryGetValue(orderId, out var order))
        return ValueTask.FromResult<Order?>(order);
    return GetFromDatabaseAsync(orderId, cancellationToken);
}

// 使用 IAsyncEnumerable 進行串流
public async IAsyncEnumerable<Order> StreamOrdersAsync(
    string customerId,
    [EnumeratorCancellation] CancellationToken cancellationToken = default)
{
    await foreach (var order in _repository.StreamAllAsync(cancellationToken))
    {
        if (order.CustomerId == customerId)
            yield return order;
    }
}

關鍵規則:

  • 一律接受 CancellationToken 並搭配 = default
  • 在函式庫程式碼中使用 ConfigureAwait(false)
  • 絕不在非同步程式碼上進行封鎖(不使用 .Result 或 .Wait())
  • 使用連結的 CancellationTokenSource 來處理逾時

Span 和 Memory

對同步的零配置操作使用 Span<T>,對非同步操作使用 Memory<T>,對大型暫存緩衝區使用 ArrayPool<T>。

請參閱 performance-and-api-design.md 以取得完整的 Span/Memory 範例和 API 設計章節。


錯誤處理:Result 型別

對於預期的錯誤,使用 Result<T, TError> 而非例外。僅將例外用於非預期的/系統錯誤。

請參閱 composition-and-error-handling.md 以取得完整的 Result 型別實作和使用範例。


避免基於反射的元程式設計

已禁止: AutoMapper、Mapster、ExpressMapper。請改用明確的對應擴充方法。當您確實需要存取私有成員時,請使用 UnsafeAccessorAttribute (.NET 8+)。

請參閱 anti-patterns-and-reflection.md 以取得完整指導。


程式碼組織

// 檔案:Domain/Orders/Order.cs

namespace MyApp.Domain.Orders;

// 1. 主要領域型別
public record Order(
    OrderId Id,
    CustomerId CustomerId,
    Money Total,
    OrderStatus Status,
    IReadOnlyList<OrderItem> Items
)
{
    public bool IsCompleted => Status is OrderStatus.Completed;

    public Result<Order, OrderError> AddItem(OrderItem item)
    {
        if (Status is not OrderStatus.Draft)
            return Result<Order, OrderError>.Failure(
                new OrderError("ORDER_NOT_DRAFT", "只能將項目新增至草稿訂單"));

        var newItems = Items.Append(item).ToList();
        var newTotal = new Money(
            Items.Sum(i => i.Total.Amount) + item.Total.Amount,
            Total.Currency);

        return Result<Order, OrderError>.Success(
            this with { Items = newItems, Total = newTotal });
    }
}

// 2. 狀態列舉
public enum OrderStatus { Draft, Submitted, Processing, Completed, Cancelled }

// 3. 相關型別
public record OrderItem(ProductId ProductId, Quantity Quantity, Money UnitPrice)
{
    public Money Total => new(UnitPrice.Amount * Quantity.Value, UnitPrice.Currency);
}

// 4. 值物件
public readonly record struct OrderId(Guid Value)
{
    public static OrderId New() => new(Guid.NewGuid());
}

// 5. 錯誤
public readonly record struct OrderError(string Code, string Message);

最佳實踐摘要

應做事項

  • 對 DTO、訊息和領域實體使用 record
  • 對值物件使用 readonly record struct
  • 利用 switch 表達式進行模式比對
  • 啟用並尊重可為 Null 的參考型別
  • 對所有 I/O 操作使用 async/await
  • 在所有非同步方法中接受 CancellationToken
  • 對高效能情境使用 Span<T> 和 Memory<T>
  • 接受抽象類型(IEnumerable<T>、IReadOnlyList<T>)
  • 對預期錯誤使用 Result<T, TError>
  • 對大型配置使用 ArrayPool<T> 來共用緩衝區
  • 偏好組合優於繼承

不應做事項

  • 不要在 record 可以運作時使用可變類別
  • 不要使用類別來實作值物件(應使用 readonly record struct)
  • 不要建立深層的繼承階層
  • 不要忽略可為 Null 的參考型別警告
  • 不要封鎖非同步程式碼(.Result、.Wait())
  • 不要在 Span<byte> 足夠時使用 byte[]
  • 不要忘記 CancellationToken 參數
  • 不要從 API 回傳可變集合
  • 不要對預期的業務錯誤擲回例外
  • 不要重複配置大型陣列(應使用 ArrayPool)

請參閱 anti-patterns-and-reflection.md 以取得詳細的反模式範例。


其他資源

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

akka-hosting-actor-patterns

Patterns for building entity actors with Akka.Hosting - GenericChildPerEntityParent, message extractors, cluster sharding abstraction, akka-reminders, and ITimeProvider. Supports both local testing and clustered production modes.

akka-net-aspire-configuration

Configure Akka.NET with .NET Aspire for local development and production deployments. Covers actor system setup, clustering, persistence, Akka.Management integration, and Aspire orchestration patterns.

akka-net-best-practices

Critical Akka.NET best practices including EventStream vs DistributedPubSub, supervision strategies, error handling, Props vs DependencyResolver, work distribution patterns, and cluster/local mode abstractions for testability.

akka-net-management

Akka.Management for cluster bootstrapping, service discovery (Kubernetes, Azure, Config), health checks, and dynamic cluster formation without static seed nodes.

akka-net-testing-patterns

Write unit and integration tests for Akka.NET actors using modern Akka.Hosting.TestKit patterns. Covers dependency injection, TestProbes, persistence testing, and actor interaction verification. Includes guidance on when to use traditional TestKit.

api-design

Design stable, compatible public APIs using extend-only design principles. Manage API compatibility, wire compatibility, and versioning for NuGet packages and distributed systems.

aspire-configuration

Configure Aspire AppHost to emit explicit app config via environment variables; keep app code free of Aspire clients and service discovery.

aspire-integration-testing

Write integration tests using .NET Aspire

aspire-service-defaults

Create a shared ServiceDefaults project for Aspire applications. Centralizes OpenTelemetry, health checks, resilience, and service discovery configuration across all services.

crap-analysis

Analyze code coverage and CRAP (Change Risk Anti-Patterns) scores to identify high-risk code. Use OpenCover format with ReportGenerator for Risk Hotspots showing cyclomatic complexity and untested code paths.

csharp-concurrency-patterns

Choosing the right concurrency abstraction in .NET - from async/await for I/O to Channels for producer/consumer to Akka.NET for stateful entity management. Avoid locks and manual synchronization unless absolutely necessary.

database-performance

Database access patterns for performance. Separate read/write models, avoid N+1 queries, use AsNoTracking, apply row limits, and never do application-side joins. Works with EF Core and Dapper.

dependency-injection-patterns

Organize DI registrations using IServiceCollection extension methods. Group related services into composable Add* methods for clean Program.cs and reusable configuration in tests.

dotnet-devcert-trust

Diagnose and fix .NET HTTPS dev certificate trust issues on Linux. Covers the full certificate lifecycle from generation to system CA bundle inclusion, with distro-specific guidance for Ubuntu, Fedora, Arch, and WSL2.

dotnet-local-tools

Managing local .NET tools with dotnet-tools.json for consistent tooling across development environments and CI/CD pipelines.

dotnet-project-structure

Modern .NET project structure including .slnx solution format, Directory.Build.props, central package management, SourceLink, version management with RELEASE_NOTES.md, and SDK pinning with global.json.

dotnet-slopwatch

Use Slopwatch to detect LLM reward hacking in .NET code changes. Run after every code modification to catch disabled tests, suppressed warnings, empty catch blocks, and other shortcuts that mask real problems.

efcore-patterns

Entity Framework Core best practices including NoTracking by default, query splitting for navigation collections, migration management, dedicated migration services, and common pitfalls to avoid.

ilspy-decompile

Understand implementation details of .NET code by decompiling assemblies. Use when you want to see how a .NET API works internally, inspect NuGet package source, view framework implementation, or understand compiled .NET binaries.

mailpit-integration

Test email sending locally using Mailpit with .NET Aspire. Captures all outgoing emails without sending them. View rendered HTML, inspect headers, and verify delivery in integration tests.

相關技能