C# 智能枚举:优化版
发布: (2026年1月2日 GMT+8 10:12)
2 min read
原文: Dev.to
Source: Dev.to
问题:LINQ 税
在第 1 部分我们用记录(record)取代了魔法数字。要查找特定状态时我们使用了 LINQ:
var status = Status.All.SingleOrDefault(x => x.Id == productStatusId);
虽然这样可行,但它有两个缺点:
- 复杂度 – 每次需要获取状态时都必须重复 LINQ 逻辑。
- 性能 – LINQ 执行线性搜索
O(n)。在高流量应用中,若状态集合很大,这会带来不必要的开销。
我们可以通过在 Status 类内部添加一个私有 Dictionary 来优化,使得无论状态有多少,都能实现瞬时的 O(1) 查找。
public record StatusValue(int Id, string Description);
public static class Status
{
public static readonly StatusValue Pending = new(1, "Pending Approval");
public static readonly StatusValue Available = new(2, "Available for Sale");
public static readonly StatusValue OutOfStock = new(3, "Out of Stock");
public static readonly StatusValue[] All = { Pending, Available, OutOfStock };
private static readonly Dictionary _lookup = All.ToDictionary(s => s.Id);
// O(1) access to the full object
public static StatusValue? Get(int id) => _lookup.GetValueOrDefault(id);
// Quick existence check
public static bool Exists(int id) => _lookup.ContainsKey(id);
// Accessing properties
public static string GetDescription(int id) => Get(id)?.Description ?? "Unknown";
}
用法
不再需要编写 LINQ 查询,服务现在可以这样做:
if (Status.Exists(userInputId))
{
var label = Status.GetDescription(userInputId);
Console.WriteLine($"Processing: {label}");
}
其他资源
- Live Demo – 在 .NET Fiddle 上尝试
- Source Code – 查看 GitHub Gist
- Dictionary 类文档 – 在官方 .NET 文档 中了解更多关于
O(1)查找引擎的信息。
Version Note: 这些性能优化针对 .NET 6+ 环境设计。