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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/397760/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 01:53:50  来源:igfitidea点击:

C#: What does the [string] indexer of Dictionary return?

c#dictionary

提问by jjnguy

What does the [string]indexer of Dictionaryreturn when the key doesn't exist in the Dictionary? I am new to C# and I can't seem to find a reference as good as the Javadocs.

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

Do I get null, or do I get an exception?

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

采纳答案by Marc Gravell

If you mean the indexer of a Dictionary<string,SomeType>, then you should see an exception (KeyNotFoundException). If you don't want it to error:

如果您指的是 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)
}

回答by Jon Skeet

As ever, the documentationis the way to find out.

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

Under Exceptions:

在例外情况下:

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

(I'm assuming you mean Dictionary<TKey,TValue>, by the way.)

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

Note that this is different from the non-generic Hashtable behaviour.

请注意,这与非通用 Hashtable 行为不同

To try to get a key's value when you don't know whether or not it exists, use TryGetValue.

要在不知道某个键是否存在时尝试获取它的值,请使用TryGetValue

回答by Kon

Alternatively to using TryGetValue, you can first check if the key exists using dict.ContainsKey(key)thus eliminating the need to declare a value prior to finding out if you'll actually need it.

作为 using 的替代方法TryGetValue,您可以首先使用 using检查键是否存在,dict.ContainsKey(key)从而无需在确定您是否真的需要它之前声明一个值。

回答by Vikas

I think you can try a

我想你可以试试

dict.ContainsKey(someKey)

to check if the Dictionary contains the key or not.

检查字典是否包含密钥。

Thanks

谢谢