我正在尝试使用我选择的键来保存集合中的项目列表。在Java中,我将简单地使用Map,如下所示:
class Test {
Map<Integer,String> entities;
public String getEntity(Integer code) {
return this.entities.get(code);
}
}
System.Collections.Generic.Hashset
不使用散列,我也不能定义自定义类型键System.Collections.Hashtable
不是泛型类
System.Collections.Generic.Dictionary
没有get(Key)
方法
发布于 2009-03-26 23:33:07
你可以索引字典,你不需要'get‘。
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;
}
使用此方法,您可以快速且无异常地获取值(如果存在)。
资源:
发布于 2009-03-26 23:34:15
Dictionary<,>是等效的。虽然它没有Get(...)方法,它确实有一个名为Item的索引属性,您可以在C#中使用索引表示法直接访问该属性:
class Test {
Dictionary<int,String> entities;
public String getEntity(int code) {
return this.entities[code];
}
}
如果要使用自定义键类型,则应考虑实现IEquatable<>并覆盖Equals(object)和GetHashCode(),除非默认的(引用或结构)相等性足以确定键的相等性。您还应该使您的键类型不可变,以防止在将键插入到字典中后发生奇怪的事情(例如,因为突变导致其哈希码改变)。
发布于 2009-03-26 23:36:09
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;
}
}
https://stackoverflow.com/questions/687942
复制相似问题