编程VB.NET 程序员(数据库,业务逻辑)

请讲述在 Visual Basic 中使用 SortedList 和 SortedDictionary 的机制。这些集合有什么区别,它们的特点是什么,在使用键和值时需要注意什么?

用 Hintsage AI 助手通过面试

回答。

问题的历史:

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

关键特点:

  • 按键排序,键的类型必须支持 IComparable 或在创建集合时指定 IComparer。
  • 在小容量时,SortedList 更省内存,但在频繁的插入/删除操作上,不如 SortedDictionary 高效。
  • 不允许键重复——尝试添加已存在的键会抛出异常。

虚假问题。

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

常见错误和反模式

  • 尝试改变现有元素的键(不可能)。
  • 作为键添加的对象未实现 IComparable/IComparer。
  • 在添加重复键时未处理异常。

生活中的例子

负面案例

实现了按标识符(userId - 键)和年龄(值)存储用户的注册表,使用 SortedList。选择了自己类型的对象(User)作为键,但未实现 IComparable。在添加用户时发生了意外异常。

优点:

  • 如果一切工作正常,排序会很方便。

缺点:

  • 在尝试插入时程序崩溃。
  • 用户在没有修改 User 类的情况下无法做任何事情。

正面案例

使用 SortedDictionary(Of Integer, User),其中键是简单类型 Integer(userId),支持比较,一切正常,用户按标识符排序。

优点:

  • 快速排序和查找。
  • 消除了 IComparable 的错误。

缺点:

  • 对于频繁的删除/添加,SortedDictionary 消耗比 SortedList 多一点内存(在大量数据中,SortedList 的插入速度较慢)。