在VB.NET中,我想將字典的內容寫入消息框。如何將字典的內容寫入消息框
字典是相當基本
Dim x As New Dictionary(Of Integer, Users)
x.Add("1", New Users("1", "Simon"))
用戶類包含2個屬性,用戶ID(整數)和用戶名(字符串)。
我在努力寫字典內容。我想寫每個字典條目到一個字符串,但我沒有成功,因爲我不斷收到錯誤消息:
參數'提示'不能轉換爲類型'字符串'。
在VB.NET中,我想將字典的內容寫入消息框。如何將字典的內容寫入消息框
字典是相當基本
Dim x As New Dictionary(Of Integer, Users)
x.Add("1", New Users("1", "Simon"))
用戶類包含2個屬性,用戶ID(整數)和用戶名(字符串)。
我在努力寫字典內容。我想寫每個字典條目到一個字符串,但我沒有成功,因爲我不斷收到錯誤消息:
參數'提示'不能轉換爲類型'字符串'。
你逝去,你指定一個整數的字符串:
修復:
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())
您的用戶類將需要重寫ToString
函數或更改ToString
調用用戶中顯示用戶的屬性名稱。
更新到用戶等級:
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
在這裏你去。
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
For Each kvp As KeyValuePair(Of Integer, Users) In x
Console.WriteLine("Key = {0}, Value = {1}", _
kvp.Key, kvp.Value)
Next kvp
類似的東西,銘記你的價值將是一個用戶對象,並作爲@LarsTech說,你應該將整數而不是字符串傳入字典
感謝您的迴應。所有似乎都運行良好,但它不輸出類內容(1,西蒙),但只是類名。我猜這是關於需要重寫ToString函數嗎?我的類是如下類用戶 私人_p1作爲字符串 私人_p2作爲字符串 的Sub New(BYVAL P1作爲字符串,BYVAL P2作爲字符串) 'TODO:完整成員初始化 _p1 = P1 _p2 = P2 完Sub End Class – Simon 2012-01-09 16:53:55
@ user1139093我更新了答案。你應該強烈考慮給你的變量更好的名字。 P1和P2不傳達任何東西。另外,我將p1更改爲一個整數。如果它需要是一個字符串,那麼你需要將你的字典改爲(Of String,String)而不是整數。 – LarsTech 2012-01-09 17:01:06
再次感謝您的回覆。我剛開始嘗試去掌握這一切,所以我絕對會用更好的名字來重命名我的變量。再一次感謝你! – Simon 2012-01-09 17:04:24