代码检查:在设置中可能无意进行线性搜索。
此检查会报告在如 HashSet<T> 或 ISet<T> 这类设置类型上,使用显式比较器调用 Contains 的情况。 该调用会经过 LINQ,可能会将原本快速的设置查找变为线性搜索。
示例
using System;
using System.Collections.Generic;
using System.Linq;
var set = new HashSet<string>();
Console.WriteLine(set.Contains("value", StringComparer.OrdinalIgnoreCase));
using System;
using System.Collections.Generic;
var set = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
Console.WriteLine(set.Contains("value"));
如何修复
此检查没有专用的快速修复方案。 典型的修复方法是使用所需比较器创建设置,或当设置已经有正确的比较器时,使用正常实例 Contains 调用。
2026年 5月 8日