代码之家  ›  专栏  ›  技术社区  ›  jjnguy Julien Chastang

C#:字典的[字符串]索引器返回什么?

  •  24
  • jjnguy Julien Chastang  · 技术社区  · 16 年前

    这是什么意思 [string] 索引器 Dictionary

    我得到了吗 null ,还是我得到了一个例外?

    4 回复  |  直到 16 年前
        1
  •  25
  •   Marc Gravell    16 年前

    如果你指的是一个 Dictionary<string,SomeType> ,那么您应该会看到一个异常( KeyNotFoundException

    SomeType value;
    if(dict.TryGetValue(key, out value)) {
       // key existed; value is set
    } else {
       // key not found; value is default(SomeType)
    }
    
        2
  •  14
  •   Jon Skeet    16 年前

    和以往一样,这项计划 documentation 这是找到答案的方法。

    在例外情况下:

    KeyNotFoundException
    The property is retrieved and key does not exist in the collection
    

    (我想你是说 Dictionary<TKey,TValue>

    请注意,这与 non-generic Hashtable behaviour

    TryGetValue .

        3
  •  5
  •   jjnguy Julien Chastang    14 年前

    我想你可以试试看

    dict.ContainsKey(someKey)
    

    检查字典是否包含该键。

    谢谢

        4
  •  4
  •   Kon    16 年前

    替代使用 TryGetValue ,您可以首先使用 dict.ContainsKey(key) 这样就不需要在确定是否需要之前声明一个值。