从 Java 世界进入 C# 世界,是否有一个 HashMap 等价物?如果不是你会推荐什么?
Dictionary https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2可能是最接近的。System.Collections.Generic.Dictionary
实施System.Collections.Generic.IDictionary https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.idictionary-2接口(类似于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
允许空键
- .NET's
Dictionary
抛出一个ArgumentNullException
如果您尝试添加空键
- Adding a duplicate key
- Java's
HashMap
将用新值替换现有值。
- .NET's
Dictionary
如果您使用,将用新值替换现有值[]
索引。如果您使用Add
方法,它会抛出一个ArgumentException
.
- Attempting to get a non-existent key
- Java's
HashMap
将返回 null。
- .NET's
Dictionary
会抛出一个KeyNotFoundException
。您可以使用TryGetValue https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2.trygetvalue方法而不是[]
索引以避免这种情况:
MyObject value = null;
if (!myDictionary.TryGetValue(key, out value)) { /* key doesn't exist */ }
Dictionary
有一个ContainsKey https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2.containskey的方法可以帮助解决前两个问题。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)