前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >CA2009:请勿对 ImmutableCollection 值调用 ToImmutableCollection

CA2009:请勿对 ImmutableCollection 值调用 ToImmutableCollection

作者头像
用户4268038
发布2022-02-26 08:30:21
3190
发布2022-02-26 08:30:21
举报
文章被收录于专栏:stcnbstcnb

规则 ID

CA2009

类别

可靠性

修复是中断修复还是非中断修复

非中断

原因

对 System.Collections.Immutable 命名空间中的不可变集合不必要地调用了 ToImmutable 方法。

规则说明

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 调用。 例如,以下两个代码片段显示了规则冲突及其解决方法:

代码语言:javascript
复制
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+。 (句点)。 从显示的选项列表中选择“删除冗余调用”。

何时禁止显示警告

除非你不关心不必要的不可变集合分配造成的性能影响,否则不要忽略此规则的冲突警告。

另请参阅

可靠性规则

性能规则

本文系外文翻译,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文系外文翻译前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档