我正在尝试使用我选择的键来保存集合中的项目列表。在 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;
}
使用此方法,您可以快速且无异常地获取值(如果存在)。
资源:
关于c# - C# 中的 Java Map 等效项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/687942/