从Java世界到c#世界,有没有HashMap的对等物?如果没有,你推荐什么?
当前回答
从c#等价于Java HashMap
我需要一个接受“null”键的字典,但似乎没有原生的字典,所以我自己写了一个。其实很简单。我继承了Dictionary,添加了一个私有字段来保存“null”键的值,然后重写了索引器。它是这样的:
public class NullableDictionnary : Dictionary<string, string>
{
string null_value;
public StringDictionary this[string key]
{
get
{
if (key == null)
{
return null_value;
}
return base[key];
}
set
{
if (key == null)
{
null_value = value;
}
else
{
base[key] = value;
}
}
}
}
希望这对将来的人有所帮助。
==========
我把它修改成这个格式
public class NullableDictionnary : Dictionary<string, object>
其他回答
字典可能是最接近的。System.Collections.Generic.Dictionary实现了System.Collections.Generic.IDictionary接口(类似于Java的Map接口)。
你应该注意的一些显著差异:
Adding/Getting items Java's HashMap has the put and get methods for setting/getting items myMap.put(key, value) MyObject value = myMap.get(key) C#'s Dictionary uses [] indexing for setting/getting items myDictionary[key] = value MyObject value = myDictionary[key] null keys Java's HashMap allows null keys .NET's Dictionary throws an ArgumentNullException if you try to add a null key Adding a duplicate key Java's HashMap will replace the existing value with the new one. .NET's Dictionary will replace the existing value with the new one if you use [] indexing. If you use the Add method, it will instead throw an ArgumentException. Attempting to get a non-existent key Java's HashMap will return null. .NET's Dictionary will throw a KeyNotFoundException. You can use the TryGetValue method instead of the [] indexing to avoid this: MyObject value = null; if (!myDictionary.TryGetValue(key, out value)) { /* key doesn't exist */ }
Dictionary's有一个ContainsKey方法可以帮助处理前两个问题。
请查看MSDN上关于Hashtable类的文档。
表示基于键的哈希代码组织的键和值对的集合。
另外,请记住,这不是线程安全的。
答案是
字典
看看我的函数,它的简单添加使用了字典中最重要的成员函数
如果列表中包含duplicate项,则此函数返回false
public static bool HasDuplicates<T>(IList<T> items)
{
Dictionary<T, bool> mp = new Dictionary<T, bool>();
for (int i = 0; i < items.Count; i++)
{
if (mp.ContainsKey(items[i]))
{
return true; // has duplicates
}
mp.Add(items[i], true);
}
return false; // no duplicates
}
我只是想说说我的意见。 这是@Powerlord的回答。
输入“null”而不是空字符串。
private static Dictionary<string, string> map = new Dictionary<string, string>();
public static void put(string key, string value)
{
if (value == null) value = "null";
map[key] = value;
}
public static string get(string key, string defaultValue)
{
try
{
return map[key];
}
catch (KeyNotFoundException e)
{
return defaultValue;
}
}
public static string get(string key)
{
return get(key, "null");
}
从c#等价于Java HashMap
我需要一个接受“null”键的字典,但似乎没有原生的字典,所以我自己写了一个。其实很简单。我继承了Dictionary,添加了一个私有字段来保存“null”键的值,然后重写了索引器。它是这样的:
public class NullableDictionnary : Dictionary<string, string>
{
string null_value;
public StringDictionary this[string key]
{
get
{
if (key == null)
{
return null_value;
}
return base[key];
}
set
{
if (key == null)
{
null_value = value;
}
else
{
base[key] = value;
}
}
}
}
希望这对将来的人有所帮助。
==========
我把它修改成这个格式
public class NullableDictionnary : Dictionary<string, object>