c# - 列表扩展方法的 Microsoft.Maintainability 错误

标签 c# list .net-3.5 extension-methods windows-ce

所以我尝试为 List 创建一些基本的扩展方法。本质上我有一个 UniqueAdd 和 UniqueAddRange。它会在添加之前检查一个值是否存在,如果它已经在列表中,它就不会添加它。这是代码:

public static class ListExtensions
{
    /// <summary>
    /// Adds only the values in the 'values' collection that do not already exist in the list. Uses list.Contains() to determine existence of
    /// previous values.
    /// </summary>
    /// <param name="list"></param>
    /// <param name="values"></param>
    public static void UniqueAddRange<T>(this List<T> list, IEnumerable<T> values)
    {
        foreach (T value in values)
        {
            list.UniqueAdd(value);
        }
    }

    /// <summary>
    /// Adds the value to the list only if it does not already exist in the list. Uses list.Contains() to determine existence of previos values.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="list"></param>
    /// <param name="value"></param>
    public static void UniqueAdd<T>(this List<T> list, T value)
    {
        if (!list.Contains(value))
        {
            list.Add(value);
        }
    }
}

构建时出现以下错误:

CA0001 : Rule=Microsoft.Maintainability#CA1506, Target=Some.Namespace.ListExtensions : Collection was modified; enumeration operation may not execute.

这是 link错误,但我不确定如何根据此信息修复我的扩展方法。它说到

Try to redesign the type or method to reduce the number of types to which it is coupled.

有谁知道我为什么会收到此错误以及如何修复我的扩展方法以免它们违反此规则?

谢谢!

PS:在有人提到它之前,我考虑过使用 HashSet 但 HashSet 在紧凑型框架中不存在。

最佳答案

我认为您的代码触发了 FxCop 中的错误,“集合已修改”是一个典型的错误。然后它决定它的错误是你的问题,catch(Exception) 风格。

寻找更新。我使用的那个不会提示你的代码(VS2010 版本)。

关于c# - 列表扩展方法的 Microsoft.Maintainability 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7604449/

相关文章:

c# - 3.5 框架中的哪些方法具有类似 String.Format 的签名?

.net - 如何用所需字符填充字符串

c# - 如何在Visual Studio中找到哪个 `method`来自哪个 `namespace`

c# - 如果 C# 中的列包含偶数,如何删除 SQL 表中的行?

python - 从字符串创建子字符串列表

c# - 处理 UserControl 中异常的正确方法

c# - ASP.NET MVC 3 如何将 ViewModel 数据保存到多个关联表

c# - RestSharp - 授权 header 未出现在 WCF REST 服务中

python - python 中正则表达式元组的 math.group 错误

Python:用 re.sub 替换列表中的多个特定单词