【C# 字典、泛型、文件流里的错误】
·
核心缺陷分析与修正方案
字典反向查找的结构性限制
哈希表设计决定了只能通过Key快速查找Value,反向查找必须遍历整个集合:
List<int> years = new();
foreach (KeyValuePair<int, string> entry in dict)
{
if (entry.Value == targetValue)
years.Add(entry.Key);
}
高频双向查询场景应维护双向字典或使用Lookup:
Dictionary<int, string> yearToCountry = new();
Dictionary<string, List<int>> countryToYears = new();
非泛型集合的现代化替代
Hashtable已过时,存在装箱拆箱开销:
// 旧方案(问题代码)
Hashtable ht = new Hashtable { {1930, "乌拉圭"} };
// 新方案(推荐方案)
Dictionary<int, string> dict = new() { {1930, "乌拉圭"} };
泛型约束与数值运算
动态类型逃避编译检查:
// 危险实现(运行时可能崩溃)
dynamic sum = default(T);
sum += array[i];
// 安全实现(.NET 7+)
static T Average<T>(T[] arr) where T : INumber<T>
{
return arr.Aggregate(T.Zero, (a, b) => a + b) / T.CreateChecked(arr.Length);
}
文件操作的精准模式控制
文件复制应使用覆盖模式:
// 错误模式(追加写入)
using var fs1 = new FileStream(path, FileMode.Append);
// 正确模式(覆盖写入)
using var fs2 = new FileStream(path, FileMode.Create);
// 路径处理规范
var fullPath = Path.Combine("D:", "data", "file.txt");
领域模型设计原则
避免使用万能容器代替领域对象:
// 反模式(弱类型设计)
Dictionary<string, object> cart = new();
// 正例(强类型设计)
public class CartItem
{
public string Sku { get; set; }
public decimal UnitPrice { get; set; }
public int Quantity { get; set; }
}
Dictionary<string, CartItem> cart = new();
关键改进原则
-
类型安全优先
- 废弃Hashtable改用Dictionary<TKey,TValue>
- 避免dynamic和object的滥用
-
API设计符合场景
- 文件操作选择匹配的FileMode
- 双向查询需求应设计对应数据结构
-
领域驱动设计
- 使用专门类替代Dictionary<string,object>
- 明确业务属性的类型约束
-
现代语法运用
- 采用INumber<T>等新特性
- 使用Path.Combine处理路径
典型问题对照表
| 问题类型 | 错误示例 | 修正方案 |
|---|---|---|
| 集合类型选择 | Hashtable | Dictionary<int,string> |
| 数值运算 | dynamic求和 | INumber<T>约束 |
| 文件操作 | FileMode.Append | FileMode.Create |
| 领域建模 | Dictionary<string,object> | 自定义CartItem类 |
更多推荐

所有评论(0)