Tecky‘s Blog

你拍一、我拍一,喝着茅台吹牛逼
  首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

HashTable和Dictionary索引器的区别

Posted on 2011-02-15 17:13  Tecky Li  阅读(2594)  评论(11编辑  收藏  举报

HashTable 索引器定义

        // Summary:
        //     Gets or sets the value associated with the specified key.
        //
        // Parameters:
        //   key:
        //     The key whose value to get or set.
        //
        // Returns:
        //     The value associated with the specified key. If the specified key is not
        //     found, attempting to get it returns null, and attempting to set it creates
        //     a new element using the specified key.
        //
        // Exceptions:
        //   System.ArgumentNullException:
        //     key is null.
        //
        //   System.NotSupportedException:
        //     The property is set and the System.Collections.Hashtable is read-only.  -or-
        //     The property is set, key does not exist in the collection, and the System.Collections.Hashtable
        //     has a fixed size.
        public virtual object this[object key] { get; set; }

里面在Returns中明确写到,当指定的key无法找到时,返回null值。所以可以使用下面的代码片段是可取的:

            Hashtable hs = new Hashtable();
            // add some elements
            if (hs["key"] == null)
            {
                //the specified key does not found in hashtable
            }

Dictionary定义:

        // Summary:
        //     Gets or sets the value associated with the specified key.
        //
        // Parameters:
        //   key:
        //     The key of the value to get or set.
        //
        // Returns:
        //     The value associated with the specified key. If the specified key is not
        //     found, a get operation throws a System.Collections.Generic.KeyNotFoundException,
        //     and a set operation creates a new element with the specified key.
        //
        // Exceptions:
        //   System.ArgumentNullException:
        //     key is null.
        //
        //   System.Collections.Generic.KeyNotFoundException:
        //     The property is retrieved and key does not exist in the collection.
        public TValue this[TKey key] { get; set; }

注释中在Returns中明确写道当指定的Key不存在时,抛出System.Collections.Generic.KeyNotFoundException,并且自动会以当前的Key创建一个新元素。

所以在使用Dictionary时,就不能通过HashTable那样来判断一个Key是否存在,而应该使用下面的代码片段:

            Dictionary<string, string> dict = new Dictionary<string, string>();
            // add some elements
            if(!dict.ContainsKey("key"))
            {
                //the specified key does not found in dictionary
            }