两个 .net 字符串是否可能具有不同的哈希值?我有一个哈希表,其中包含关键“路径”。当我循环遍历表中的元素以打印它时,我可以看到键存在。
然而,当试图查找它时,没有匹配的元素。调试表明我要查找的字符串与我作为 key 提供的字符串具有不同的哈希值。
此代码位于 CaSTLe Monorail 项目中,使用 brail 作为 View 引擎。我正在寻找的 key 是由这样的盲文插入的:
UrlHelper.Link(node.CurrentPage.LinkText, {@params: {@path: "/Page1"}})
然后,在此方法中(在自定义 IRoutingRule 中):
public string CreateUrl(System.Collections.IDictionary parameters)
{
PrintDictionaryToLog(parameters);
string url;
if (parameters.Contains("path")) {
url = (string)parameters["path"];
}
else {
return null;
}
}
key 被打印到日志中,但函数返回 null。我不知道这甚至可能是 .net 字符串的问题,但我猜这是某种编码问题?
哦,这是单声道运行。
根据要求,这是日志中的相关行:
2010-03-08 22:58:00,504 [7] DEBUG Knickle.Framework.Routing.PageRoute (null) - Parameters: {System.String controller=null, System.String path=Page1, System.String path=/Page1, System.String action=null, System.String area=null}
此外,这里我在日志打印调用上方添加了一行代码:
parameters.Add("path", "Page1");
查看日志,您会注意到有两个“路径”键。调试器在表中的不同位置显示这两个键。
最佳答案
这是 GetHashCode for Strings 上指向 MSDN 的链接。如果它们相等,则哈希码应该匹配,但如果它们不相等,它们仍可能具有相同的哈希值(无论这种可能性有多小)。
http://msdn.microsoft.com/en-us/library/system.string.gethashcode.aspx
来自文章:
If two string objects are equal, the GetHashCode method returns identical values. However, there is not a unique hash code value for each unique string value. Different strings can return the same hash code.
关于.NET 哈希表 - "Same"键,不同的哈希,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2405026/