以下代码应该抛出异常,以防止添加重复的集合项。
ICollection<T> collection = new List<T>();
public void Add(T item)
{
if (collection.Contain(item))
{
throw new SomeExceptionType()
}
collection.Add(item);
}
什么标准异常类型最合适?
以下代码应该抛出异常,以防止添加重复的集合项。
ICollection<T> collection = new List<T>();
public void Add(T item)
{
if (collection.Contain(item))
{
throw new SomeExceptionType()
}
collection.Add(item);
}
好的,Dictionary<,>.Add()
会在存在重复键时抛出ArgumentException
异常,所以我想这可能是一个先例。
Linq使用两个新的异常DuplicateNameException和DuplicateKeyException,如果你正在使用system.data程序集,则可以使用它们。
InvalidOperationException
:
由于参数值的有效性取决于对象的状态(即是否为true的当方法调用对于对象的当前状态无效时引发的异常。
collection.Contains(item)
),因此我认为这是最好的异常处理方式。参数异常是正确的异常(字典也使用该异常)
InvalidOperationException
,因为添加已经存在于集合中的对象是无效的。System.ArgumentException
我会抛出一个 ArgumentException。这就是泛型 System.Collections.Generic.SortedList<>
在其 Add
方法中所做的。
来自 .NET Framework 2.0 代码:
public void Add(TKey key, TValue value)
{
if (key == null)
{
System.ThrowHelper.ThrowArgumentNullException(System.ExceptionArgument.key);
}
int num = Array.BinarySearch<TKey>(this.keys, 0, this._size, key, this.comparer);
if (num >= 0)
{
System.ThrowHelper.ThrowArgumentException(System.ExceptionResource.Argument_AddingDuplicate);
}
this.Insert(~num, key, value);
}