我正在尝试使用我选择的键来保存集合中的项目列表。在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)
方法
答案 0 :(得分:176)
你可以索引词典,你不需要'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;
}
使用此方法,您可以快速且无异常地获取值(如果存在)。
资源:
答案 1 :(得分:17)
词典&LT;,&GT;是等价的。虽然它没有Get(...)方法,但它确实有一个名为Item的索引属性,您可以使用索引表示法直接在C#中访问:
class Test {
Dictionary<int,String> entities;
public String getEntity(int code) {
return this.entities[code];
}
}
如果您想使用自定义密钥类型,那么您应该考虑实现IEquatable&lt;&gt;除非默认(引用或结构)相等足以确定键的相等性,否则重写Equals(object)和GetHashCode()。如果密钥在插入字典后发生变异(例如,因为变异导致其哈希码发生变化),您还应该使密钥类型不可变,以防止发生奇怪的事情。
答案 2 :(得分:10)
class Test
{
Dictionary<int, string> entities;
public string GetEntity(int code)
{
// java's get method returns null when the key has no mapping
// so we'll do the same
string val;
if (entities.TryGetValue(code, out val))
return val;
else
return null;
}
}