C#中的Java的HashMap相当于 [英] C# Java HashMap equivalent

查看:2162
本文介绍了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接口(这类似于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 and get methods for setting/getting items
          • myMap.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 an ArgumentNullException 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 the Item property. If you use the Add method, it will instead throw an ArgumentException.

          • Java的的HashMap 将返回null。

          • .NET的词典将抛出一个 KeyNotFoundException 。您可以使用<$c$c>TryGetValue方法,而不是项目属性来避免这种情况:结果
            MyObject的价值= NULL;
            如果(!myDictionary.TryGetValue(键,值)){/ *键不存在* /}

          • Java's HashMap will return null.
          • .NET's Dictionary will throw a KeyNotFoundException. You can use the TryGetValue method instead of the Item 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方法,可以帮助处理previous两个问题。

          Dictionary's has a ContainsKey method that can help deal with the previous two problems.

          这篇关于C#中的Java的HashMap相当于的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆