C# Java HashMap 等价物 [英] C# Java HashMap equivalent

查看:43
本文介绍了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?

推荐答案

Dictionary 可能是最接近的.System.Collections.Generic.Dictionary 实现 System.Collections.Generic.IDictionary 接口(类似于 Java 的 Map 接口).

您应该注意的一些显着差异:

Some notable differences that you should be aware of:

  • 添加/获取项目
    • Java 的 HashMap 具有用于设置/获取项目的 putget 方法
      • myMap.put(key, value)
      • MyObject 值 = myMap.get(key)
      • 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[key] = value
          • MyObject 值 = myDictionary[key]
          • Java 的 HashMap 允许空键
          • 如果您尝试添加空键,
          • .NET 的 Dictionary 会抛出 ArgumentNullException
          • Java's HashMap allows null keys
          • .NET's Dictionary throws an ArgumentNullException if you try to add a null key
          • Java 的 HashMap 会将现有值替换为新值.
          • 如果您使用 [] 索引,
          • .NET 的 Dictionary 将用新值替换现有值.如果您使用 Add 方法,它会改为抛出 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 [] indexing. If you use the Add method, it will instead throw an ArgumentException.
          • Java 的 HashMap 将返回 null.
          • .NET 的 Dictionary 将抛出 KeyNotFoundException.您可以使用 TryGetValue 方法而不是 [] 索引以避免这种情况:
            MyObject 值 = null;if (!myDictionary.TryGetValue(key, out value)) {/* 键不存在 */}
          • Java's HashMap will return null.
          • .NET's Dictionary will throw a KeyNotFoundException. You can use the TryGetValue method instead of the [] indexing to avoid this:
            MyObject value = null; if (!myDictionary.TryGetValue(key, out value)) { /* key doesn't exist */ }

          Dictionary 有一个 ContainsKey 方法可以帮助处理前两个问题.

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

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

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