如果键不存在,C# Dictionary<int, int> 查找会发生什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2138982/
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
What happens to C# Dictionary<int, int> lookup if the key does not exist?
提问by deltanovember
I tried checking for null but the compiler warns that this condition will never occur. What should I be looking for?
我尝试检查 null 但编译器警告这种情况永远不会发生。我应该寻找什么?
采纳答案by Jon Skeet
Assuming you want to get the value if the key doesexist, use Dictionary<TKey, TValue>.TryGetValue
:
假设您想在键确实存在的情况下获取值,请使用Dictionary<TKey, TValue>.TryGetValue
:
int value;
if (dictionary.TryGetValue(key, out value))
{
// Key was in dictionary; "value" contains corresponding value
}
else
{
// Key wasn't in dictionary; "value" is now 0
}
(Using ContainsKey
and then the the indexer makes it look the key up twice, which is pretty pointless.)
(使用ContainsKey
然后索引器使它查找键两次,这是毫无意义的。)
Note that even if you wereusing reference types, checking for null wouldn't work - the indexer for Dictionary<,>
will throw an exception if you request a missing key, rather than returning null. (This is a big difference between Dictionary<,>
and Hashtable
.)
请注意,即使您正在使用引用类型,检查空值也不起作用 -Dictionary<,>
如果您请求缺少键,索引器将抛出异常,而不是返回空值。(这是Dictionary<,>
和之间的很大区别Hashtable
。)
回答by ChrisF
If you're just checking before trying to add a new value, use the ContainsKey
method:
如果您只是在尝试添加新值之前进行检查,请使用以下ContainsKey
方法:
if (!openWith.ContainsKey("ht"))
{
openWith.Add("ht", "hypertrm.exe");
}
If you're checking that the value exists, use the TryGetValue
method as described in Jon Skeet's answer.
如果您正在检查该值是否存在,请使用TryGetValue
Jon Skeet 的回答中所述的方法。
回答by ZombieSheep
You should check for Dictionary.ContainsKey(int key) before trying to pull out the value.
在尝试提取值之前,您应该检查 Dictionary.ContainsKey(int key)。
Dictionary<int, int> myDictionary = new Dictionary<int, int>();
myDictionary.Add(2,4);
myDictionary.Add(3,5);
int keyToFind = 7;
if(myDictionary.ContainsKey(keyToFind))
{
myValueLookup = myDictionay[keyToFind];
// do work...
}
else
{
// the key doesn't exist.
}
回答by ZombieSheep
ContainsKeyis what you're looking for.
containsKey就是您要查找的内容。
回答by Razzie
You should probably use:
您可能应该使用:
if(myDictionary.ContainsKey(someInt))
{
// do something
}
The reason why you can't check for null is that the key here is a value type.
不能检查 null 的原因是这里的键是一个值类型。
回答by antik
The Dictionary throws a KeyNotFound
exception in the event that the dictionary does not contain your key.
如果字典KeyNotFound
不包含您的密钥,则字典会引发异常。
As suggested, ContainsKey
is the appropriate precaution. TryGetValue
is also effective.
正如所建议的那样,ContainsKey
是适当的预防措施。 TryGetValue
也是有效的。
This allows the dictionary to store a value of null more effectively. Without it behaving this way, checking for a null result from the [] operator would indicate either a null value OR the non-existance of the input key which is no good.
这允许字典更有效地存储 null 值。如果没有这种行为,检查 [] 运算符的空结果将指示空值或输入键的不存在,这是不好的。
回答by sheamus
A helper class is handy:
一个助手类很方便:
public static class DictionaryHelper
{
public static TVal Get<TKey, TVal>(this Dictionary<TKey, TVal> dictionary, TKey key, TVal defaultVal = default(TVal))
{
TVal val;
if( dictionary.TryGetValue(key, out val) )
{
return val;
}
return defaultVal;
}
}
回答by Nitika Chopra
int result= YourDictionaryName.TryGetValue(key, out int value) ? YourDictionaryName[key] : 0;
If the key is present in the dictionary, it returns the value of the key otherwise it returns 0.
如果键存在于字典中,则返回键的值,否则返回 0。
Hope, this code helps you.
希望,此代码可以帮助您。
回答by Pablo Company Ramírez
Consider the option of encapsulating this particular dictionary and provide a method to return the value for that key:
考虑封装这个特定字典的选项,并提供一种方法来返回该键的值:
public static class NumbersAdapter
{
private static readonly Dictionary<string, string> Mapping = new Dictionary<string, string>
{
["1"] = "One",
["2"] = "Two",
["3"] = "Three"
};
public static string GetValue(string key)
{
return Mapping.ContainsKey(key) ? Mapping[key] : key;
}
}
Then you can manage the behaviour of this dictionary.
然后你可以管理这本字典的行为。
For example here: if the dictionary doesn't have the key, it returns key that you pass by parameter.
例如这里:如果字典没有键,它将返回您通过参数传递的键。