C#:Dictionary的[string]索引器返回什么?

jjn*_*guy 24 c# dictionary

当词典中不存在键时返回的[string]索引器是什么Dictionary?我是C#的新手,我似乎找不到像Javadocs那样好的参考.

我得到了null,还是我得到了例外?

Mar*_*ell 25

如果你的意思是a的索引器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)
}
Run Code Online (Sandbox Code Playgroud)


Jon*_*eet 14

与以往一样,文档是找出答案的方法.

在例外情况下:

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

(Dictionary<TKey,TValue>顺便说一下,我假设你的意思.)

请注意,这与非泛型Hashtable行为不同.

要在不知道密钥是否存在时尝试获取密钥的值,请使用TryGetValue.


Vik*_*kas 5

我想你可以尝试一下

dict.ContainsKey(someKey)
Run Code Online (Sandbox Code Playgroud)

检查词典是否包含密钥.

谢谢