值
规则 ID
CA1829
类别
“性能”
修复是中断修复还是非中断修复
非中断
原因
对支持等效且更高效的 Length 或 Count 属性的类型使用了 Count LINQ 方法。
规则说明
此规则在具有等效但更高效的 Length 或 Count 属性以提取相同数据的类型的集合上标记 Count LINQ 方法调用。 Length 或 Count 属性不枚举集合,因此更高效。
此规则标记具有 Length 属性的以下集合类型上的 Count 调用:
System.Array
System.Collections.Immutable.ImmutableArray<T>
此规则标记具有 Count 属性的以下集合类型上的 Count 调用:
System.Collections.ICollection
System.Collections.Generic.ICollection<T>
System.Collections.Generic.IReadOnlyCollection<T>
分析后的集合类型可能会在将来扩展,以涵盖更多的情况。
如何解决冲突
若要解决冲突,请将 Count 方法调用替换为使用 Length 或 Count 属性访问。 例如,以下两个代码片段显示了规则冲突及其解决方法:
using System.Collections.Generic;
using System.Linq;
class C
{
public int GetCount(int[] array)
=> array.Count();
public int GetCount(ICollection<int> collection)
=> collection.Count();
}
using System.Collections.Generic;
class C
{
public int GetCount(int[] array)
=> array.Length;
public int GetCount(ICollection<int> collection)
=> collection.Count;
}
提示
Visual Studio 中为此规则提供了代码修补程序。 若要使用它,请将光标置于冲突上,然后按 Ctrl+。 (句点)。 从显示的选项列表中选择“在可用时使用 Length/Count 属性,而不是 Count()”。
何时禁止显示警告
如果不关心不必要的集合枚举计算计数对性能产生的影响,则可禁止显示此规则的冲突警告。
相关规则
CA1826:使用属性,而不是 Linq Enumerable 方法
CA1827:如果可以使用 Any,请勿使用 Count/LongCount
CA1828:如果可以使用 AnyAsync,请勿使用 CountAsync/LongCountAsync
另请参阅
性能规则
本文系外文翻译,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文系外文翻译,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。