问题的历史:
SortedList 和 SortedDictionary 类型的集合在 .NET 中出现,用于方便地以按键排序的方式存储键值对。它们在按键快速访问的同时支持排序时使用。
问题:
常见错误与在这些集合之间的选择不当、使用不合适类型的键(不支持 IComparable),以及对插入重复键行为的错误预期有关。
解决方案:
在 Visual Basic 中使用类 SortedList(Of TKey, TValue) 和 SortedDictionary(Of TKey, TValue) 来存储排序后的数据。
示例代码:
Dim sortedList As New SortedList(Of String, Integer)() sortedList.Add("Alex", 27) sortedList.Add("Mike", 34) Dim age As Integer = sortedList("Alex") ' 27 Dim sortedDict As New SortedDictionary(Of Integer, String)() sortedDict.Add(3, "Three") sortedDict.Add(1, "One") For Each pair In sortedDict Console.WriteLine(pair.Key & ": " & pair.Value) Next
关键特点:
1. 是否可以改变 SortedList 或 SortedDictionary 中现有元素的键?
不能,无法改变现有元素的键。要“改变”键,必须删除原始对并添加一个具有更正键的新对。
2. 尝试添加已经存在的键时会发生什么异常?
会抛出 ArgumentException。
Dim sl As New SortedList(Of Integer, String)() sl.Add(1, "One") sl.Add(1, "Repeat") ' ArgumentException
3. 如果在键中使用不实现 IComparable 的类型会发生什么?
编译器会允许创建集合,但在尝试添加第一个元素时会抛出 InvalidOperationException。
Class MyObj End Class Dim sd As New SortedDictionary(Of MyObj, String)() sd.Add(New MyObj(), "test") ' Exception
实现了按标识符(userId - 键)和年龄(值)存储用户的注册表,使用 SortedList。选择了自己类型的对象(User)作为键,但未实现 IComparable。在添加用户时发生了意外异常。
优点:
缺点:
使用 SortedDictionary(Of Integer, User),其中键是简单类型 Integer(userId),支持比较,一切正常,用户按标识符排序。
优点:
缺点: