版权声明:本文为博主原创文章,转载请在显著位置标明本文出处以及作者网名,未经作者允许不得用于商业目的。
Hashtable 和 Dictionary 都是一个键值对的集合
其中
Hashtable 包含的单个键值对为 DictionaryEntry 结构
Dictionary 包含的单个键值对为 KeyValuePair 结构
共同点:
1、都只能有唯一的键(Key),如果要增加同样的键会报错,但是错误提示不一样:
这个是Hashtable报错:
这个是Dictionary报错:
2、键不能为空
3、不同的键可以对应相同的值
不同点:
1、Hashtable Add方法键值参数类型都是Object,Dictionary Add方法需要和构造函数(New)时的参数类型对应。由于涉及到装箱和拆箱,所以HashTable在数据量较大的时候会比Dictionary慢。
2、Hashtable在枚举输出的时候无顺序,Dictionary在枚举输出的时候按照增加顺序输出。
3、DictionaryEntry的键值是可以读写,但是KeyValuePair的键值只读
最后是一个DictionaryEntry操作的示例:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim aa As DictionaryEntry
aa.Key = 1
aa.Value = "122"
txtInfo.Text = aa.Key & ":" & aa.Value & ControlChars.CrLf
txtInfo.Text &= "=========" & ControlChars.CrLf
Dim cc As New clsStudent
cc.Name = "姓名"
cc.ID = 12
aa.Key = cc
aa.Value = "这是一个测试"
Dim dd As clsStudent
dd = CType(aa.Key, clsStudent)
txtInfo.Text &= ControlChars.CrLf & dd.Name & ":" & aa.Value
End Sub
Public Class clsStudent
Public Property Name As String
Public Property ID As Integer
End Class
由于.net平台下C#和vb.NET很相似,本文也可以为C#爱好者提供参考。
学习更多vb.net知识,请参看vb.net 教程 目录