我试图使用sorteddictionary来存储文件中的一些数据,但是出现了一些非常奇怪的密钥复制异常。我想出了下一个复制我的问题的代码示例:

var dict = new SortedDictionary<string, string>();
dict.Add("Æ", "qwerty"); // "aesc" (aka "ash"), single symbol
Console.WriteLine(dict["AE"]); // outputs "qwerty" for two-symbol string "AE"
dict.Add("AE", ""); // ArgumentException: An entry with the same key already exists.

This code on .NET Fiddle
不过,这在普通字典里是不可能的,我最终决定改用它。但我还是想知道为什么分类的问题是什么?不幸的是,尽管微软最近开放了一些.NET源代码,但我自己无法在谷歌上搜索答案(有很多与AES相关的噪音),也无法调试SortedDictionary的代码。
这个类似乎隐式地运行了一些字符串预处理/规范化函数,但我不能相信这是一个真正的原因。
你知道为什么吗?提前谢谢!

最佳答案

这是因为文化。例如,尝试new SortedDictionary(StringComparer.Ordinal)
字典行为不同的原因是它使用EqualityComparer<TKey>.Default,而sorteddictionary使用Comparer<TKey>.Default

10-07 22:33