dotnet
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chinese.NET
.NET
Overview
概述
.NET is Microsoft's open-source, cross-platform framework for building web APIs, cloud services, desktop applications, mobile apps, games, IoT, and AI/ML solutions. The modern .NET platform (6+) unifies what were formerly separate runtimes (.NET Framework, .NET Core, Mono) into a single SDK. C# is the primary language, with F# for functional programming. The ecosystem spans 400,000+ NuGet packages, first-party Azure integration, and tooling through Visual Studio, VS Code, and JetBrains Rider.
.NET是微软推出的开源跨平台框架,用于构建Web API、云服务、桌面应用、移动应用、游戏、物联网(IoT)以及AI/ML解决方案。现代.NET平台(6及以上版本)将之前独立的运行时(.NET Framework、.NET Core、Mono)统一为单一SDK。C#是主要开发语言,F#用于函数式编程。该生态系统包含超过40万个NuGet包,原生集成Azure云服务,并支持Visual Studio、VS Code和JetBrains Rider等开发工具。
Knowledge Map
知识图谱
dotnet/
├── ai/ # ML.NET, ONNX, Azure AI, Microsoft.Extensions.AI, agents (A2A, MCP)
├── cli/ # Spectre.Console, CliWrap, command-line cheatsheet
├── cloud/ # Aspire, Azure Functions, Dapr, Orleans, service discovery
├── configuration/ # Extensions.Configuration, caching, feature flags, OpenFeature
├── data/ # EF Core, Dapper, Redis, Lucene.NET, FluentStorage
├── dependency-injection/ # Extensions.DI, Generic Host, Spring.NET
├── documentation/ # OpenAPI / Swagger
├── eventing/ # MediatR, MassTransit, NServiceBus, Rebus, Wolverine, Brighter, Akka.NET
├── functional/ # F#, Language.Ext, FParsec, Optional, pidgin
├── general/ # Humanizer, ImageSharp, NodaTime, Stateless, worker services, cheatsheet
├── localization/ # i18n, resource-based localization, MessageFormat
├── logging/ # Serilog, NLog, Extensions.Logging
├── mapping/ # AutoMapper, Mapperly
├── networking/ # gRPC, DotNetty, MimeKit, System.IO.Pipelines, Twilio
├── observability/ # OTLP logging, OpenTelemetry conventions
├── project-system/ # MSBuild/csproj, Roslyn analyzers, source generators, EditorConfig, Fody
├── reactive/ # Rx.NET, System.Threading.Channels, DynamicData, IAsyncEnumerable
├── resilience/ # Polly, Extensions.Resilience
├── security/ # ASP.NET Identity, cryptography, authorization (Topaz, Enforcer)
├── serialization/ # Protobuf-net, Bond, Hyperion, FluentSerializer
├── testing/ # Testcontainers, Moq, AutoFixture, Pact, Reqnroll, Playwright
├── ui/ # MAUI, Avalonia, Blazor, Uno Platform, Blazorise, MonoGame, Unity
├── validation/ # FluentValidation, Validot, Parse Don't Validate, CommunityToolkit.Guard
└── web/ # ASP.NET Core, SignalR, YARP, Ocelot, GraphQL, Refit, Orchard CMSdotnet/
├── ai/ # ML.NET, ONNX, Azure AI, Microsoft.Extensions.AI, agents (A2A, MCP)
├── cli/ # Spectre.Console, CliWrap, command-line cheatsheet
├── cloud/ # Aspire, Azure Functions, Dapr, Orleans, service discovery
├── configuration/ # Extensions.Configuration, caching, feature flags, OpenFeature
├── data/ # EF Core, Dapper, Redis, Lucene.NET, FluentStorage
├── dependency-injection/ # Extensions.DI, Generic Host, Spring.NET
├── documentation/ # OpenAPI / Swagger
├── eventing/ # MediatR, MassTransit, NServiceBus, Rebus, Wolverine, Brighter, Akka.NET
├── functional/ # F#, Language.Ext, FParsec, Optional, pidgin
├── general/ # Humanizer, ImageSharp, NodaTime, Stateless, worker services, cheatsheet
├── localization/ # i18n, resource-based localization, MessageFormat
├── logging/ # Serilog, NLog, Extensions.Logging
├── mapping/ # AutoMapper, Mapperly
├── networking/ # gRPC, DotNetty, MimeKit, System.IO.Pipelines, Twilio
├── observability/ # OTLP logging, OpenTelemetry conventions
├── project-system/ # MSBuild/csproj, Roslyn analyzers, source generators, EditorConfig, Fody
├── reactive/ # Rx.NET, System.Threading.Channels, DynamicData, IAsyncEnumerable
├── resilience/ # Polly, Extensions.Resilience
├── security/ # ASP.NET Identity, cryptography, authorization (Topaz, Enforcer)
├── serialization/ # Protobuf-net, Bond, Hyperion, FluentSerializer
├── testing/ # Testcontainers, Moq, AutoFixture, Pact, Reqnroll, Playwright
├── ui/ # MAUI, Avalonia, Blazor, Uno Platform, Blazorise, MonoGame, Unity
├── validation/ # FluentValidation, Validot, Parse Don't Validate, CommunityToolkit.Guard
└── web/ # ASP.NET Core, SignalR, YARP, Ocelot, GraphQL, Refit, Orchard CMSChoosing Guide
选型指南
| Problem | Sub-Skill | Notes |
|---|---|---|
| Build a web API or microservice | | Minimal APIs for simple endpoints, controllers for complex APIs |
| Add real-time push to a web app | | WebSocket abstraction with automatic fallback to SSE/long-polling |
| Reverse proxy or API gateway | | YARP for high-perf programmatic proxy, Ocelot for config-driven gateway |
| GraphQL API | | Hot Chocolate server with filtering, sorting, subscriptions |
| Access a relational database | | Full ORM with migrations, change tracking, LINQ queries |
| Lightweight SQL queries | | Micro-ORM, raw SQL with object mapping, best for read-heavy paths |
| Distributed cache | | Redis for shared cache, IMemoryCache/IDistributedCache for local/hybrid |
| Event-driven / CQRS architecture | | In-process mediator; combine with |
| Message bus (RabbitMQ, Kafka, Azure SB) | | Abstraction over transports with sagas, retries, and outbox pattern |
| Build a .NET Aspire app | | Orchestrate multi-project apps with built-in service discovery and telemetry |
| Serverless functions | | Isolated worker model for Azure Functions with DI and middleware |
| Resilience (retries, circuit breakers) | | Configurable policies; use |
| Structured logging | | Sinks for Console, Seq, Elasticsearch, Application Insights |
| Object mapping | | Source-generator-based mapper (zero reflection, compile-time safe) |
| Input validation | | Fluent rules with DI integration and ASP.NET Core auto-validation |
| Integration testing with real DBs | | Docker-based throwaway containers for Postgres, SQL Server, Redis |
| Mocking in unit tests | | Proxy-based mocking with LINQ setup expressions |
| Contract testing | | Consumer-driven contract tests for microservice boundaries |
| BDD / Gherkin | | SpecFlow successor — Given/When/Then with .NET 8+ support |
| Cross-platform desktop app | | XAML-based UI for Windows, macOS, Linux, iOS, Android, WebAssembly |
| Mobile + desktop from one codebase | | Microsoft's official cross-platform UI framework (.NET 8+) |
| Interactive web UI in C# | | Server-side or WebAssembly rendering with Razor components |
| Functional programming in C# | | Immutable collections, Option/Either monads, pattern matching extensions |
| F# language guidance | | Type providers, computation expressions, pipelines, domain modeling |
| AI/ML inference | | Unified abstraction for OpenAI, Azure AI, Ollama, and custom providers |
| Train ML models in .NET | | AutoML, classification, regression, anomaly detection, recommendation |
| Build a CLI tool | | Rich terminal UI with tables, trees, progress bars, prompts |
| Source generators | | Compile-time code generation with Roslyn incremental generators |
| Roslyn code analysis | | Custom analyzers and code fixes for enforcing team conventions |
| 问题场景 | 子技能 | 说明 |
|---|---|---|
| 构建Web API或微服务 | | 简单端点使用Minimal APIs,复杂API使用控制器 |
| 为Web应用添加实时推送功能 | | WebSocket抽象层,可自动降级为SSE/长轮询 |
| 反向代理或API网关 | | YARP适用于高性能可编程代理,Ocelot适用于配置驱动的网关 |
| GraphQL API开发 | | 带过滤、排序、订阅功能的Hot Chocolate服务器 |
| 访问关系型数据库 | | 完整ORM,支持迁移、变更跟踪、LINQ查询 |
| 轻量级SQL查询 | | 微型ORM,支持原生SQL与对象映射,适用于读密集型场景 |
| 分布式缓存 | | Redis用于共享缓存,IMemoryCache/IDistributedCache用于本地/混合缓存 |
| 事件驱动/CQRS架构 | | 进程内中介者模式;跨服务场景可结合 |
| 消息总线(RabbitMQ、Kafka、Azure SB) | | 对多种传输协议的抽象,支持saga、重试和事务箱模式 |
| 构建.NET Aspire应用 | | 编排多项目应用,内置服务发现与遥测功能 |
| 无服务器函数 | | Azure Functions的独立工作者模型,支持DI与中间件 |
| 弹性处理(重试、熔断) | | 可配置策略;DI集成场景使用 |
| 结构化日志 | | 支持Console、Seq、Elasticsearch、Application Insights等输出端 |
| 对象映射 | | 基于源代码生成的映射器(零反射,编译时安全) |
| 输入验证 | | 流畅式规则定义,支持DI集成与ASP.NET Core自动验证 |
| 结合真实数据库的集成测试 | | 基于Docker的一次性容器,支持Postgres、SQL Server、Redis等 |
| 单元测试中的模拟 | | 基于代理的模拟框架,支持LINQ设置表达式 |
| 契约测试 | | 微服务边界的消费者驱动契约测试 |
| BDD/Gherkin测试 | | SpecFlow的继任者,支持.NET 8+的Given/When/Then语法 |
| 跨平台桌面应用 | | 基于XAML的UI框架,支持Windows、macOS、Linux、iOS、Android、WebAssembly |
| 单代码库开发移动与桌面应用 | | 微软官方跨平台UI框架(.NET 8+) |
| 用C#开发交互式Web UI | | 基于Razor组件的服务器端或WebAssembly渲染 |
| C#中的函数式编程 | | 不可变集合、Option/Either单体、模式匹配扩展 |
| F#语言指导 | | 类型提供器、计算表达式、管道操作、领域建模 |
| AI/ML推理 | | 对OpenAI、Azure AI、Ollama及自定义提供者的统一抽象 |
| 在.NET中训练ML模型 | | 自动机器学习、分类、回归、异常检测、推荐系统 |
| 构建CLI工具 | | 丰富的终端UI,支持表格、树形结构、进度条、交互提示 |
| 源代码生成器 | | 基于Roslyn的增量源代码生成器,实现编译时代码生成 |
| Roslyn代码分析 | | 自定义分析器与代码修复,用于强制执行团队编码规范 |
.NET Version Landscape
.NET版本全景
| Version | Release | Support | Key Features |
|---|---|---|---|
| .NET 6 | Nov 2021 | LTS (ended Nov 2024) | Minimal APIs, hot reload, |
| .NET 7 | Nov 2022 | STS (ended May 2024) | Native AOT for console apps, rate limiting middleware, output caching |
| .NET 8 | Nov 2023 | LTS (until Nov 2026) | .NET Aspire, |
| .NET 9 | Nov 2024 | STS (until May 2026) | |
| 版本 | 发布时间 | 支持状态 | 核心特性 |
|---|---|---|---|
| .NET 6 | 2021年11月 | LTS(2024年11月结束支持) | Minimal APIs、热重载、 |
| .NET 7 | 2022年11月 | STS(2024年5月结束支持) | 控制台应用原生AOT、限流中间件、输出缓存 |
| .NET 8 | 2023年11月 | LTS(至2026年11月) | .NET Aspire、 |
| .NET 9 | 2024年11月 | STS(至2026年5月) | |
Choosing a Version
版本选择建议
- Starting a new project? Use .NET 8 (LTS) for stability, or .NET 9 for latest features.
- In production with .NET 6? Plan migration to .NET 8 — .NET 6 support has ended.
- Need native AOT? .NET 8+ supports AOT for ASP.NET Core minimal APIs and gRPC.
- Using Aspire for orchestration? Requires .NET 8+.
- 启动新项目? 使用.NET 8(LTS版本)以获得稳定性,或使用.NET 9获取最新特性。
- 生产环境使用.NET 6? 计划迁移至.NET 8——.NET 6的支持已结束。
- 需要原生AOT? .NET 8+支持ASP.NET Core Minimal APIs和gRPC的AOT编译。
- 使用Aspire进行编排? 需要.NET 8及以上版本。
C# Quick Reference
C#快速参考
Modern C# Features (10-13)
现代C#特性(10-13版本)
csharp
// Global usings (C# 10) — reduce boilerplate across files
global using System.Text.Json;
global using Microsoft.Extensions.Logging;
// File-scoped namespaces (C# 10)
namespace MyApp.Services;
// Records with positional syntax — immutable data types
public record OrderPlaced(Guid OrderId, string CustomerId, decimal Total, DateTime PlacedAt);
// Primary constructors (C# 12) — DI without field ceremony
public class OrderService(IOrderRepository repo, ILogger<OrderService> logger)
{
public async Task<Order> GetAsync(Guid id)
{
logger.LogInformation("Fetching order {OrderId}", id);
return await repo.FindAsync(id) ?? throw new NotFoundException(id);
}
}
// Collection expressions (C# 12)
int[] numbers = [1, 2, 3, 4, 5];
List<string> names = ["Alice", "Bob", "Charlie"];
ReadOnlySpan<byte> header = [0x48, 0x54, 0x54, 0x50];
// Pattern matching with list patterns (C# 11)
string Describe(int[] values) => values switch
{
[] => "empty",
[var single] => $"one item: {single}",
[var first, .., var last] => $"from {first} to {last}",
};
// Raw string literals (C# 11) — no escaping needed
var json = """
{
"name": "Widget",
"price": 29.99,
"tags": ["electronics", "sale"]
}
""";
// Required members (C# 11)
public class Config
{
public required string ConnectionString { get; init; }
public required int MaxRetries { get; init; }
public TimeSpan Timeout { get; init; } = TimeSpan.FromSeconds(30);
}
// Switch expressions with property patterns
decimal CalculateDiscount(Order order) => order switch
{
{ Total: > 1000, Customer.IsPremium: true } => order.Total * 0.15m,
{ Total: > 500 } => order.Total * 0.10m,
{ Customer.IsPremium: true } => order.Total * 0.05m,
_ => 0m,
};csharp
// Global usings (C# 10) — 减少文件间的样板代码
global using System.Text.Json;
global using Microsoft.Extensions.Logging;
// File-scoped namespaces (C# 10)
namespace MyApp.Services;
// 带位置语法的Records — 不可变数据类型
public record OrderPlaced(Guid OrderId, string CustomerId, decimal Total, DateTime PlacedAt);
// 主构造函数(C# 12)—— 无需私有字段的依赖注入
public class OrderService(IOrderRepository repo, ILogger<OrderService> logger)
{
public async Task<Order> GetAsync(Guid id)
{
logger.LogInformation("Fetching order {OrderId}", id);
return await repo.FindAsync(id) ?? throw new NotFoundException(id);
}
}
// 集合表达式(C# 12)
int[] numbers = [1, 2, 3, 4, 5];
List<string> names = ["Alice", "Bob", "Charlie"];
ReadOnlySpan<byte> header = [0x48, 0x54, 0x54, 0x50];
// 带列表模式的模式匹配(C# 11)
string Describe(int[] values) => values switch
{
[] => "empty",
[var single] => $"one item: {single}",
[var first, .., var last] => $"from {first} to {last}",
};
// 原始字符串字面量(C# 11)—— 无需转义
var json = """
{
"name": "Widget",
"price": 29.99,
"tags": ["electronics", "sale"]
}
""";
// 必填成员(C# 11)
public class Config
{
public required string ConnectionString { get; init; }
public required int MaxRetries { get; init; }
public TimeSpan Timeout { get; init; } = TimeSpan.FromSeconds(30);
}
// 带属性模式的Switch表达式
decimal CalculateDiscount(Order order) => order switch
{
{ Total: > 1000, Customer.IsPremium: true } => order.Total * 0.15m,
{ Total: > 500 } => order.Total * 0.10m,
{ Customer.IsPremium: true } => order.Total * 0.05m,
_ => 0m,
};Key NuGet Package Categories
核心NuGet包分类
| Category | Go-To Packages | When to Use |
|---|---|---|
| Web Framework | ASP.NET Core (built-in) | REST APIs, Razor Pages, Blazor, gRPC |
| ORM | EF Core, Dapper | EF Core for full ORM, Dapper for raw SQL performance |
| Validation | FluentValidation, Validot | Fluent rule definitions, DI-friendly, auto-wire with ASP.NET |
| Mapping | Mapperly, AutoMapper | Mapperly for source-gen (zero reflection), AutoMapper for convention-based |
| Serialization | System.Text.Json, Protobuf-net | STJ for JSON (built-in), Protobuf for binary/gRPC |
| Logging | Serilog, NLog | Structured logging with sinks for Seq, Elastic, AppInsights |
| Testing | xUnit, Moq, AutoFixture, Testcontainers | xUnit as test framework, Moq for mocks, Testcontainers for integration |
| Resilience | Polly, Extensions.Resilience | Retry, circuit breaker, timeout, rate limiter policies |
| Messaging | MassTransit, MediatR, NServiceBus | MassTransit for bus abstraction, MediatR for in-process CQRS |
| DI | Extensions.DI (built-in) | Constructor injection, scoped/transient/singleton lifetimes |
| Caching | Extensions.Caching, StackExchange.Redis | IMemoryCache for local, IDistributedCache for Redis/SQL |
| HTTP Client | Refit, RestSharp | Refit for interface-defined clients, RestSharp for simpler REST calls |
| CLI | Spectre.Console, System.CommandLine | Rich terminal UIs, argument parsing, help generation |
| Cloud | .NET Aspire, Azure.Identity | Aspire for orchestration, Azure.Identity for managed identity auth |
| 分类 | 首选包 | 使用场景 |
|---|---|---|
| Web框架 | ASP.NET Core(内置) | REST API、Razor Pages、Blazor、gRPC |
| 对象关系映射(ORM) | EF Core、Dapper | EF Core用于完整ORM场景,Dapper用于原生SQL高性能场景 |
| 验证 | FluentValidation、Validot | 流畅式规则定义,支持DI,可与ASP.NET自动集成 |
| 对象映射 | Mapperly、AutoMapper | Mapperly基于源代码生成(零反射),AutoMapper基于约定配置 |
| 序列化 | System.Text.Json、Protobuf-net | System.Text.Json(内置)用于JSON序列化,Protobuf用于二进制/gRPC序列化 |
| 日志 | Serilog、NLog | 结构化日志,支持Seq、Elasticsearch、Application Insights等输出端 |
| 测试 | xUnit、Moq、AutoFixture、Testcontainers | xUnit作为测试框架,Moq用于模拟对象,Testcontainers用于集成测试 |
| 弹性处理 | Polly、Extensions.Resilience | 重试、熔断、超时、限流策略 |
| 消息传递 | MassTransit、MediatR、NServiceBus | MassTransit用于消息总线抽象,MediatR用于进程内CQRS |
| 依赖注入(DI) | Extensions.DI(内置) | 构造函数注入,支持单例、作用域、瞬时生命周期 |
| 缓存 | Extensions.Caching、StackExchange.Redis | IMemoryCache用于本地缓存,IDistributedCache用于Redis/SQL分布式缓存 |
| HTTP客户端 | Refit、RestSharp | Refit基于接口定义客户端,RestSharp用于简单REST调用 |
| CLI工具 | Spectre.Console、System.CommandLine | 丰富的终端UI、参数解析、帮助文档生成 |
| 云服务 | .NET Aspire、Azure.Identity | Aspire用于应用编排,Azure.Identity用于托管身份认证 |
Best Practices
最佳实践
-
Use the latest LTS release (.NET 8) for production workloads. LTS releases receive 3 years of security patches and bug fixes.
-
Enable nullable reference types () in every project. This catches null-reference bugs at compile time:
<Nullable>enable</Nullable>xml<PropertyGroup> <TargetFramework>net8.0</TargetFramework> <Nullable>enable</Nullable> <ImplicitUsings>enable</ImplicitUsings> </PropertyGroup> -
Usepattern for configuration instead of reading values directly. This provides validation, reload support, and testability:
IOptions<T>csharppublic class SmtpOptions { public const string Section = "Smtp"; public required string Host { get; init; } public int Port { get; init; } = 587; public required string FromAddress { get; init; } } // In Program.cs builder.Services.AddOptions<SmtpOptions>() .BindConfiguration(SmtpOptions.Section) .ValidateDataAnnotations() .ValidateOnStart(); -
Prefer records for data transfer objects and events. Records provide value equality, immutability, and concise syntax. Usefor heap-allocated (default) and
record classfor stack-allocated small types.record struct -
Use primary constructors for DI in services and controllers (C# 12). This eliminates boilerplatefields while keeping constructor injection.
private readonly -
Avoid— it swallows exceptions. Always return
async voidorTaskfrom async methods. The only exception is event handlers.ValueTask -
Useeverywhere — pass it through all async call chains so requests can be cancelled cleanly when clients disconnect:
CancellationTokencsharpapp.MapGet("/orders/{id}", async (Guid id, IOrderRepository repo, CancellationToken ct) => await repo.FindAsync(id, ct) is { } order ? Results.Ok(order) : Results.NotFound()); -
Register services with the correct lifetime —for stateless/thread-safe services,
Singletonfor per-request state (EF DbContext),Scopedfor lightweight stateless operations. Never inject Scoped into Singleton.Transient -
Use source generators over reflection where available (Mapperly, System.Text.Json source gen, Roslyn analyzers). Source generators run at compile time, eliminate reflection costs, and are compatible with Native AOT.
-
Structure solutions with clear project boundaries — separate API host, domain logic, infrastructure, and tests into distinct projects. Useand enforce dependency direction (domain has no external references).
<ProjectReference>
-
使用最新LTS版本(.NET 8)运行生产工作负载。LTS版本提供3年的安全补丁和Bug修复支持。
-
在所有项目中启用可空引用类型()。这可以在编译时捕获空引用Bug:
<Nullable>enable</Nullable>xml<PropertyGroup> <TargetFramework>net8.0</TargetFramework> <Nullable>enable</Nullable> <ImplicitUsings>enable</ImplicitUsings> </PropertyGroup> -
使用模式管理配置,而非直接读取配置值。该模式提供验证、重载支持和可测试性:
IOptions<T>csharppublic class SmtpOptions { public const string Section = "Smtp"; public required string Host { get; init; } public int Port { get; init; } = 587; public required string FromAddress { get; init; } } // 在Program.cs中 builder.Services.AddOptions<SmtpOptions>() .BindConfiguration(SmtpOptions.Section) .ValidateDataAnnotations() .ValidateOnStart(); -
优先使用Records作为数据传输对象和事件。Records提供值相等性、不可变性和简洁语法。默认使用(堆分配),小型类型使用
record class(栈分配)。record struct -
在服务和控制器中使用主构造函数进行DI(C# 12)。这可以消除样板化的字段,同时保留构造函数注入的优势。
private readonly -
避免使用——它会吞噬异常。异步方法应始终返回
async void或Task。唯一的例外是事件处理程序。ValueTask -
在所有异步方法中使用——将其传递到所有异步调用链中,以便客户端断开连接时可以干净地取消请求:
CancellationTokencsharpapp.MapGet("/orders/{id}", async (Guid id, IOrderRepository repo, CancellationToken ct) => await repo.FindAsync(id, ct) is { } order ? Results.Ok(order) : Results.NotFound()); -
使用正确的生命周期注册服务——用于无状态/线程安全服务,
Singleton用于每个请求的状态(如EF DbContext),Scoped用于轻量级无状态操作。切勿将Scoped服务注入到Singleton服务中。Transient -
优先使用源代码生成而非反射(如Mapperly、System.Text.Json源代码生成、Roslyn分析器)。源代码生成在编译时运行,消除反射开销,且兼容Native AOT。
-
以清晰的项目边界组织解决方案——将API宿主、领域逻辑、基础设施和测试拆分为独立项目。使用并强制依赖方向(领域层不依赖外部引用)。
<ProjectReference>