在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