.NET 框架 (3.5) 中是否有一个集合(除了 Dictionary)在添加重复项时会引发异常?
HashSet 不会在这里抛出异常:
HashSet<string> strings = new HashSet<string>();
strings.Add("apple");
strings.Add("apple");
而字典则:
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("dude", "dude");
dict.Add("dude", "dude"); //throws exception
编辑:是否有一个没有 (Key, Value) 的集合可以做到这一点?如果可能的话,我也想要 AddRange...
我推出了自己的:
public class Uniques<T> : HashSet<T>
{
public Uniques()
{ }
public Uniques(IEnumerable<T> collection)
{
AddRange(collection);
}
public void Add(T item)
{
if (!base.Add(item))
{
throw new ArgumentException("Item already exists");
}
}
public void AddRange(IEnumerable<T> collection)
{
foreach (T item in collection)
{
Add(item);
}
}
}
最佳答案
但是如果该值已经存在,HashSet.Add 方法将返回 false - 这还不够吗?
HashSet<string> set = new HashSet<string>();
...
if (!set.Add("Key"))
/* Not added */
关于添加重复项时引发异常的 .NET 集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1679500/