c# - C# 中的 Java Map 等效项

标签 c# java generics collections

我正在尝试使用我选择的键来保存集合中的项目列表。在 Java 中,我会简单地使用 Map 如下:

class Test {
  Map<Integer,String> entities;

  public String getEntity(Integer code) {
    return this.entities.get(code);
  }
}

在 C# 中是否有等效的方法? System.Collections.Generic.Hashset 不使用哈希,我无法定义自定义类型键 System.Collections.Hashtable 不是泛型类
System.Collections.Generic.Dictionary 没有 get(Key) 方法

最佳答案

你可以索引字典,你不需要'get'。

Dictionary<string,string> example = new Dictionary<string,string>();
...
example.Add("hello","world");
...
Console.Writeline(example["hello"]);

测试/获取值的有效方法是 TryGetValue(感谢 Earwicker):

if (otherExample.TryGetValue("key", out value))
{
    otherExample["key"] = value + 1;
}

使用此方法,您可以快速且无异常地获取值(如果存在)。

资源:

Dictionary-Keys

Try Get Value

关于c# - C# 中的 Java Map 等效项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/687942/

相关文章:

c# - 参数字典包含不可为 null 类型 'id' 的参数 'System.Int32' 的 null 条目

c# - 如何在 asp :checkboxlist 中获取所选项目的计数

java - 无符号 16 位和 64 位整数

java - 使用 JDK 1.8 时泛型引用不明确

Java Enum 作为 Enum 中的泛型类型

c# - 如何连接一行中的所有列值,然后将 DataTable 中的所有行连接成一个字符串?

c# - MVVM 和异步属性

java - 我在解密使用 RSA 生成的公钥 (.jks) 编码的 128 位 AES key 时遇到 BadPaddingException

java - Android Button OnClickListener 仅在单击其他按钮后触发

java - 使用动态类引用时抑制警告