Community编程与开发github.com

现代C#编码规范

使用记录、模式匹配、值对象、async/await、Span<T>/Memory<T>及最佳API设计模式,编写现代、高性能的C#代码。强调利用C# 12+特性进行函数式编程。

现代C#编码规范 是什么?

该技能为开发者提供了编写现代、高性能C#代码的全面指南,涵盖C# 9至12的关键语言特性及最佳实践。它强调不可变性、类型安全、模式匹配、异步编程和零分配模式。核心原则包括默认使用`record`类型实现不可变数据、通过`readonly record struct`实现值对象、利用`switch`表达式进行模式匹配、以及使用`Span<T>`和`Memory<T>`进行高性能操作。该技能还倡导组合优于继承、采用`Result<T, TError>`处理预期错误、避免基于反射的框架如AutoMapper,并在API设计中使用`IReadOnlyList<T>`等抽象。所有最佳实践均配有详细的代码示例,并指导开发者查阅配套的参考文件以获取更深入的实现。

兼容平台~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. 类型安全 - 利用可空引用类型和值对象
  3. 现代模式匹配 - 广泛使用switch表达式和模式
  4. 无处不在的异步 - 优先使用支持取消功能的异步API
  5. 零分配模式 - 在性能关键代码中使用Span<T>和Memory<T>
  6. API设计 - 接受抽象类型,返回适当具体的类型
  7. 组合优于继承 - 避免抽象基类,优先使用组合
  8. 值对象作为结构体 - 使用readonly record struct实现值对象

语言模式

用于不可变数据的记录(C# 9+)

使用record类型处理DTO、消息、事件和领域实体。

// 简单的不可变DTO
public record CustomerDto(string Id, string Name, string Email);

// 带构造函数验证的记录
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;
    }
}

// 带集合的记录 - 使用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 获取完整的模式匹配示例。


可空引用类型(C# 8+)

在项目中启用可空引用类型并显式处理null。

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

// 显式可空性
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);
}

组合优于继承

避免抽象基类。 使用接口+组合。使用静态辅助方法处理共享逻辑。使用带工厂方法的记录处理变体。

请参阅 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;
    }
}

关键规则:

  • 始终接受带= default的CancellationToken
  • 在库代码中使用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表达式的模式匹配
  • 启用并尊重可空引用类型
  • 对所有I/O操作使用async/await
  • 在所有异步方法中接受CancellationToken
  • 对高性能场景使用Span<T>和Memory<T>
  • 接受抽象类型(IEnumerable<T>、IReadOnlyList<T>)
  • 对预期错误使用Result<T, TError>
  • 使用ArrayPool<T>池化大型缓冲区
  • 优先使用组合而非继承

禁止事项

  • 不要在可以使用record的地方使用可变类
  • 不要对值对象使用类(应使用readonly record struct)
  • 不要创建深度继承层次结构
  • 不要忽略可空引用类型警告
  • 不要在异步代码上阻塞(.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.

相关技能