| 属性 | 值 |
|---|---|
| 规则 ID | CA2009 |
| 标题 | 请勿对 ImmutableCollection 值调用 ToImmutableCollection |
| 类别 | 可靠性 |
| 修复是导致破坏性更改还是非破坏性更改 | 非中断 |
| 在 .NET 10 中默认启用 | 作为一种建议 |
| 适用的语言 | C# 和 Visual Basic |
原因
对 ToImmutable 命名空间中的不可变集合不必要地调用了 System.Collections.Immutable 方法。
规则说明
System.Collections.Immutable 命名空间包含用于定义不可变集合的类型。 此规则分析以下不可变集合类型:
- System.Collections.Immutable.ImmutableArray<T>
- System.Collections.Immutable.ImmutableList<T>
- System.Collections.Immutable.ImmutableHashSet<T>
- System.Collections.Immutable.ImmutableSortedSet<T>
- System.Collections.Immutable.ImmutableDictionary<TKey,TValue>
- System.Collections.Immutable.ImmutableSortedDictionary<TKey,TValue>
这些类型定义了从现有 IEnumerable<T> 集合创建新的不可变集合的扩展方法。
- ImmutableArray<T> 定义 ToImmutableArray。
- ImmutableList<T> 定义 ToImmutableList。
- ImmutableHashSet<T> 定义 ToImmutableHashSet。
- ImmutableSortedSet<T> 定义 ToImmutableSortedSet。
- ImmutableDictionary<TKey,TValue> 定义 ToImmutableDictionary。
- ImmutableSortedDictionary<TKey,TValue> 定义 ToImmutableSortedDictionary。
这些扩展方法旨在将可变集合转换为不可变集合。 但是,调用方可能会意外地将不可变集合作为输入传递给这些方法。 这可能表示存在性能和/或功能问题。
- 性能问题:对不可变集合执行了不必要的装箱、拆箱和/或运行时类型检查。
- 可能的功能问题:调用方假定要在可变集合上操作,而其实际拥有的是一个不可变集合。
如何解决违规
若要解决冲突,请删除对不可变集合的冗余 ToImmutable 调用。 例如,以下两个代码片段显示了规则冲突及其解决方法:
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
public class C
{
public void M(IEnumerable<int> collection, ImmutableArray<int> immutableArray)
{
// This is fine.
M2(collection.ToImmutableArray());
// This leads to CA2009.
M2(immutableArray.ToImmutableArray());
}
private void M2(ImmutableArray<int> immutableArray)
{
Console.WriteLine(immutableArray.Length);
}
}
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
public class C
{
public void M(IEnumerable<int> collection, ImmutableArray<int> immutableArray)
{
// This is fine.
M2(collection.ToImmutableArray());
// This is now fine.
M2(immutableArray);
}
private void M2(ImmutableArray<int> immutableArray)
{
Console.WriteLine(immutableArray.Length);
}
}
提示
Visual Studio 中为此规则提供了代码修补程序。 若要使用它,请将光标置于违规上,然后按 "Ctrl
何时禁止显示警告
除非你不在意不必要的不可变集合分配对性能的影响,否则不要抑制此规则的违规警告。
抑制警告
如果只想抑制单个冲突,请将预处理器指令添加到源文件以禁用该规则,然后重新启用该规则。
#pragma warning disable CA2009
// The code that's violating the rule is on this line.
#pragma warning restore CA2009
若要对文件、文件夹或项目禁用该规则,请在none中将其严重性设置为 。
[*.{cs,vb}]
dotnet_diagnostic.CA2009.severity = none
有关详细信息,请参阅如何禁止显示代码分析警告。