Loading...
Loading...
Compare original and translation side by side
record structSpan<T>recordreadonlyinitrequiredrecord structSpan<T>recordreadonlyinitrequired| Feature | Usage | Example |
|---|---|---|
| Primary constructors | DI injection, eliminate field assignments | |
| Collection expressions | | |
| Records | DTOs, value objects, immutable data | |
| Small stack-allocated value types | |
| Pattern matching | Switch expressions, list/property patterns | |
| List patterns | Deconstruct arrays/lists | |
| Zero-allocation slicing | |
| Raw string literals | Multi-line SQL, JSON, XML | |
| Enforce initialization | |
| Null/type/property check | |
| 特性(Feature) | 用法(Usage) | 示例(Example) |
|---|---|---|
| Primary constructors | 依赖注入(DI)、消除字段赋值 | |
| Collection expressions | 用 | |
| Records | 数据传输对象(DTO)、值对象、不可变数据 | |
| 小型栈分配值类型 | |
| Pattern matching | 开关表达式、列表/属性模式 | |
| List patterns | 解构数组/列表 | |
| 零分配切片 | |
| Raw string literals | 多行SQL、JSON、XML | |
| 强制初始化 | |
| 空值/类型/属性检查 | |
fieldfield// GOOD — field keyword for validation in auto-property
public class Product
{
public string Name
{
get => field;
set => field = value?.Trim() ?? throw new ArgumentNullException(nameof(value));
}
public decimal Price
{
get => field;
set => field = value >= 0 ? value : throw new ArgumentOutOfRangeException(nameof(value));
}
}// GOOD — 使用field关键字实现自动属性验证
public class Product
{
public string Name
{
get => field;
set => field = value?.Trim() ?? throw new ArgumentNullException(nameof(value));
}
public decimal Price
{
get => field;
set => field = value >= 0 ? value : throw new ArgumentOutOfRangeException(nameof(value));
}
}fieldfieldpublic class ProductCatalog
{
// Lazy-load on first access — no manual Lazy<T> or backing field
public IReadOnlyList<Product> Products
{
get => field ??= LoadProducts();
}
private static List<Product> LoadProducts() => /* expensive load */;
}public class ProductCatalog
{
// 首次访问时延迟加载 —— 无需手动使用Lazy<T>或后备字段
public IReadOnlyList<Product> Products
{
get => field ??= LoadProducts();
}
private static List<Product> LoadProducts() => /* 耗时加载逻辑 */;
}fieldfield// INotifyPropertyChanged without manual backing fields
public class OrderViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler? PropertyChanged;
public string CustomerName
{
get => field;
set
{
if (field == value) return;
field = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(CustomerName)));
}
} = "";
public decimal Total
{
get => field;
set
{
if (field == value) return;
field = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Total)));
}
}
}// 无需手动后备字段的INotifyPropertyChanged实现
public class OrderViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler? PropertyChanged;
public string CustomerName
{
get => field;
set
{
if (field == value) return;
field = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(CustomerName)));
}
} = "";
public decimal Total
{
get => field;
set
{
if (field == value) return;
field = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Total)));
}
}
}extension// GOOD — extension block (shipped C# 14 syntax)
public static class OrderExtensions
{
extension(Order order)
{
public decimal TotalWithTax => order.Total * 1.2m;
public bool IsHighValue => order.Total > 1000m;
public string ToSummary() =>
$"Order #{order.Id}: {order.Total:C} ({order.Items.Count} items)";
}
// Static extension members use the type (no receiver instance)
extension(Order)
{
public static Order Empty => Order.Create("none", [], DateTimeOffset.MinValue);
}
}
// Callers see them as if declared on Order
if (order.IsHighValue) { /* ... */ }thisextension// GOOD — 扩展块(C# 14正式语法)
public static class OrderExtensions
{
extension(Order order)
{
public decimal TotalWithTax => order.Total * 1.2m;
public bool IsHighValue => order.Total > 1000m;
public string ToSummary() =>
$"Order #{order.Id}: {order.Total:C} ({order.Items.Count} items)";
}
// 静态扩展成员使用类型(无需接收者实例)
extension(Order)
{
public static Order Empty => Order.Create("none", [], DateTimeOffset.MinValue);
}
}
// 调用者可像调用Order自身成员一样使用它们
if (order.IsHighValue) { /* ... */ }this// BAD — manual backing field when field keyword works
private string _name;
public string Name
{
get => _name;
set => _name = value ?? throw new ArgumentNullException();
}
// BAD — old-style collection initialization
var list = new List<int>() { 1, 2, 3 };
// BAD — Tuple instead of record for domain types
(string Name, decimal Price) product = ("Widget", 9.99m);
// GOOD — record
public record Product(string Name, decimal Price);// BAD — 当field关键字可用时,仍手动声明后备字段
private string _name;
public string Name
{
get => _name;
set => _name = value ?? throw new ArgumentNullException();
}
// BAD — 旧式集合初始化方式
var list = new List<int>() { 1, 2, 3 };
// BAD — 领域类型使用Tuple而非record
(string Name, decimal Price) product = ("Widget", 9.99m);
// GOOD — 使用record
public record Product(string Name, decimal Price);// BAD — deeply nested pattern that's hard to read
if (order is { Customer: { Address: { Country: { Code: "US" } } } })
// GOOD — extract to a clear method or use sequential checks
if (order.Customer.Address.Country.Code == "US")// BAD — 深度嵌套的模式难以阅读
if (order is { Customer: { Address: { Country: { Code: "US" } } } })
// GOOD — 提取为清晰的方法或使用顺序检查
if (order.Customer.Address.Country.Code == "US")varvar// BAD — what type is this?
var result = Process(order);
// GOOD — explicit type when not obvious
Result<Order> result = Process(order);
// Also GOOD — var is fine when type is apparent
var orders = new List<Order>();// BAD — 无法明确此变量类型
var result = Process(order);
// GOOD — 类型不明确时使用显式类型
Result<Order> result = Process(order);
// 同样GOOD — 类型明显时使用var没问题
var orders = new List<Order>();| Scenario | Recommendation |
|---|---|
| DTO / API contract | |
| Small value object (2-3 fields) | |
| Service with DI | Primary constructor |
| Collection creation | Collection expression |
| Property with validation | |
| Multi-line string (SQL, JSON) | Raw string literal |
| Slicing strings/arrays | |
| Type checking + extraction | Pattern matching with |
| Enforced initialization | |
| Adding methods to external types | Extension members |
| 场景(Scenario) | 推荐方案(Recommendation) |
|---|---|
| DTO / API契约 | |
| 小型值对象(2-3个字段) | |
| 带依赖注入的服务 | Primary constructor |
| 集合创建 | 集合表达式 |
| 带验证的属性 | |
| 多行字符串(SQL、JSON) | 原始字符串字面量 |
| 字符串/数组切片 | |
| 类型检查 + 提取 | 使用 |
| 强制初始化 | |
| 为外部类型添加方法 | 扩展成员 |