I tried checking for null but the compiler warns that this condition will never occur. What should I be looking for?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
Assuming you want to get the value if the key does exist, use
Dictionary<TKey, TValue>.TryGetValue
:(Using
ContainsKey
and then the the indexer makes it look the key up twice, which is pretty pointless.)Note that even if you were using 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 betweenDictionary<,>
andHashtable
.)If the key is present in the dictionary, it returns the value of the key otherwise it returns 0.
Hope, this code helps you.
You should probably use:
The reason why you can't check for null is that the key here is a value type.
ContainsKey is what you're looking for.
A helper class is handy:
You should check for Dictionary.ContainsKey(int key) before trying to pull out the value.