C#中的Java的HashMap相当于 [英] C# Java HashMap equivalent
本文介绍了C#中的Java的HashMap相当于的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
从Java世界进入了一个C#的是有一个HashMap相同呢?如果不是你有什么建议?
Coming from a Java world into a C# one is there a HashMap equivalent? If not what would you recommend?
推荐答案
词典
可能是最接近。 System.Collections.Generic.Dictionary
实施<一个href=\"http://msdn.microsoft.com/en-us/library/s4ys34ea.aspx\"><$c$c>System.Collections.Generic.IDictionary$c$c>接口(这类似于Java的地图
接口)。
一些显着的差异,你应该知道的:
Some notable differences that you should be aware of:
- 添加/获取项目
- Java的HashMap具有
把
和GET
设置/获取项目的方法-
myMap.put(键,值)
-
MyObject的价值= myMap.get(键)
- Adding/Getting items
- Java's HashMap has the
put
andget
methods for setting/getting itemsmyMap.put(key, value)
MyObject value = myMap.get(key)
-
myDictionary.Item [关键] =值
-
MyObject的价值= myDictionary.Item [关键]
myDictionary.Item[key] = value
MyObject value = myDictionary.Item[key]
- Java的
的HashMap
允许null键 - .NET的
词典
引发ArgumentNullException
如果您尝试添加一个空键
- Java's
HashMap
allows null keys - .NET's
Dictionary
throws anArgumentNullException
if you try to add a null key
- Java的
的HashMap
将用新的替换现有的值。 - .NET的
词典
将如果您使用项目
属性与新的替换现有的值。如果您使用添加
方法,这反而抛出的ArgumentException
。
- Java's
HashMap
will replace the existing value with the new one. - .NET's
Dictionary
will replace the existing value with the new one if you use theItem
property. If you use theAdd
method, it will instead throw anArgumentException
.
- Java的
的HashMap
将返回null。 - .NET的
词典
将抛出一个KeyNotFoundException
。您可以使用<$c$c>TryGetValue$c$c>方法,而不是项目
属性来避免这种情况:结果MyObject的价值= NULL;
如果(!myDictionary.TryGetValue(键,值)){/ *键不存在* /}
- Java's
HashMap
will return null. - .NET's
Dictionary
will throw aKeyNotFoundException
. You can use theTryGetValue
method instead of theItem
property to avoid this:
MyObject value = null; if (!myDictionary.TryGetValue(key, value)) { /* key doesn't exist */ }
词典
的有<一个href=\"https://msdn.microsoft.com/en-us/library/kw5aaea4%28v=vs.110%29.aspx\"><$c$c>ContainsKey$c$c>方法,可以帮助处理previous两个问题。Dictionary
's has aContainsKey
method that can help deal with the previous two problems.这篇关于C#中的Java的HashMap相当于的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- Java's HashMap has the
-
- Java的HashMap具有
查看全文