问题
我正在尝试使用我选择的键来保存集合中的项目列表。在Java中,我只想使用Map如下:
class Test {
Map<Integer,String> entities;
public String getEntity(Integer code) {
return this.entities.get(code);
}
}
有没有一种在C#中执行此操作的等效方法?System.Collections.Generic.Hashset
不使用哈希,我无法定义自定义类型keySystem.Collections.Hashtable
不是泛型类System.Collections.Generic.Dictionary
没有aget(Key)
方法
#1 热门回答(169 赞)
你可以索引词典,你不需要'得到'。
Dictionary<string,string> example = new Dictionary<string,string>();
...
example.Add("hello","world");
...
Console.Writeline(example["hello"]);
测试/获取值的有效方法是TryGetValue
(thanx to Earwicker):
if (otherExample.TryGetValue("key", out value))
{
otherExample["key"] = value + 1;
}
使用此方法,你可以快速且无异常地获取值(如果存在)。
资源:
Dictionary-KeysTry Get Value
#2 热门回答(17 赞)
字典<,>是等价的。虽然它没有Get(...)方法,但它确实有一个名为Item的索引属性,你可以使用索引表示法直接在C#中访问它:
class Test {
Dictionary<int,String> entities;
public String getEntity(int code) {
return this.entities[code];
}
}
如果要使用自定义键类型,则应考虑实现IEquatable <>并重写Equals(object)和GetHashCode(),除非默认(引用或结构)相等足以确定键的相等性。如果密钥在插入字典后发生变异(例如因为变异导致其哈希代码发生变化),你还应该使密钥类型不可变,以防止发生奇怪的事情。
#3 热门回答(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;
}
}