代码之家  ›  专栏  ›  技术社区  ›  klashar

尝试将重复项添加到集合时应引发什么异常类型?[闭门]

  •  23
  • klashar  · 技术社区  · 17 年前

    ICollection<T> collection = new List<T>();
    
    public void Add(T item)
    {
        if (collection.Contain(item))
        {
              throw new SomeExceptionType()
        }
    
        collection.Add(item);
    }
    

    哪种标准异常类型最合适?

    8 回复  |  直到 7 年前
        1
  •  40
  •   Pavel Minaev    17 年前

    好, Dictionary<,>.Add() 投掷 ArgumentException

        2
  •  9
  •   amarnath chatterjee    9 年前

    Linq使用了另外两个异常 重复名称异常 和 重复键异常

        3
  •  6
  •   Brandon    17 年前

    ArgumentException 可能是最好的。这是参数无效时引发的异常。

        4
  •  4
  •   Andrew Hare    17 年前

    我会用 InvalidOperationException :

    异常发生时引发的异常 方法调用对于的无效 对象的当前状态。

    collection.Contains(item)

    确保向异常添加了一条好消息,以明确调用者的问题所在。

        5
  •  3
  •   cyberconte    17 年前

        6
  •  1
  •   Ben M    17 年前
    System.ArgumentException
    
        7
  •  1
  •   Thomas Levesque    17 年前

    我得说 InvalidOperationException ,因为添加已在集合中的对象无效

        8
  •  1
  •   Paul Williams    17 年前

    我会抛出一个例外。这是通用的 System.Collections.Generic.SortedList<> Add

        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);
        }