在VB.net中執行字符串連接時,我發現嘗試連接整數字符串時出現奇怪的運行時錯誤。Visual Basic強制轉換 - 從字符串轉換爲類型'Double'無效
這裏是我的小提琴:https://dotnetfiddle.net/NY4Y4V
Imports System
Imports System.Collections.Generic
Public Module Module1
Public Sub Main()
Dim t As Dictionary(Of Int32, DateTime?) = new Dictionary(Of Int32, DateTime?)
t.Add(12345, new DateTime())
For Each f As KeyValuePair(Of Int32, DateTime?) In t
Console.WriteLine("Test string {" + f.Key + "}.")
Next
End Sub
End Module
具體來說,我很好奇,爲什麼例外:
System.InvalidCastException:從字符串轉換 「測試字符串{」 鍵入 '雙師型'無效。
正在發生。我知道,這是一個簡單的解決方法,如果我明確的整數轉換爲字符串:
Console.WriteLine("Test string {" + f.Key.ToString() + "}.")
我只是好奇發生了什麼場景會出現此錯誤鑄造後面。我在代碼中的任何地方都沒有觸及雙打,所以我不確定爲什麼要輸入'Double'來投射這個問題。
'如果你想保證字符串連接,Option Strict與否,你可以使用&operator'很高興你在你的文章中提到這個。我不知道有多少次這樣咬我工作的人以及我遇到的一些事情。好帖子! – Codexer
很好的答案,謝謝! – thomasdclark