【发布时间】:2011-09-29 23:22:51
【问题描述】:
所以我尝试为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,但我不确定如何根据这些信息修复我的扩展方法。它说
尝试重新设计类型或方法以减少与之耦合的类型数量。
有谁知道我为什么会收到此错误以及如何修复我的扩展方法以使其不违反此规则?
谢谢!
PS:之前有人提过,我已经考虑过使用HashSet,但是HashSet在compact框架中并不存在。
【问题讨论】:
标签: c# list .net-3.5 extension-methods windows-ce