在VB.NET中,我想将字典的内容写入消息框。
字典是相当基本的
Dim x As New Dictionary(Of Integer, Users)
x.Add("1", New Users("1", "Simon"))
用户类包含2个属性,用户ID(整数)和用户名(字符串)。
我正在努力写字典内容。我想将每个字典条目写入字符串但我没有成功,因为我不断收到错误消息:
参数'Prompt'无法转换为'String'类型。
答案 0 :(得分:4)
您正在传递一个指定整数的字符串:
修正:
Dim x As New Dictionary(Of Integer, Users)
x.Add(1, New Users(1, "Simon"))
然后显示内容:
Dim sb As New StringBuilder
For Each item As KeyValuePair(Of Integer, Users) In x
sb.AppendLine(item.Key & ") " & item.Value.ToString)
Next
MessageBox.Show(sb.ToString())
您的Users类需要覆盖ToString
函数或更改{USER}中显示用户名称的属性的ToString
调用。
更新到Users类:
Public Class Users
Private _p1 As Integer
Private _p2 As String
Sub New(ByVal p1 As Integer, ByVal p2 As String)
_p1 = p1
_p2 = p2
End Sub
Public Overrides Function ToString() As String
Return _p2
End Function
End Class
答案 1 :(得分:1)
你走了。
Dim sbMessage As New System.Text.StringBuilder(500)
For Each wKey As Integer In x.Keys
sbMessage.Append("Key = ").Append(wKey).Append(", Value = ").Append(x.Item(wKey).ToString()).AppendLine()
Next
MessageBox.Show(sbMessage.ToString)
为了使其有用,您需要覆盖Users类中的ToString方法。例如,假设此类中有ID和名称:
Public Overrides Function ToString() As String
Dim sbText As New System.Text.StringBuilder(500)
sbText.Append("ID = ").Append(Me.Id).Append(", Name = ").Append(Me.Name)
Return sbText.ToString
End Function
答案 2 :(得分:1)
For Each kvp As KeyValuePair(Of Integer, Users) In x
Console.WriteLine("Key = {0}, Value = {1}", _
kvp.Key, kvp.Value)
Next kvp
类似的东西,记住你的Value将是一个Users对象,并且正如@LarsTech所说,你应该将整数而不是字符串传入字典