【发布时间】:2016-05-12 15:31:39
【问题描述】:
在 VB.net 中进行字符串连接时,我注意到在尝试将字符串与整数连接时出现奇怪的运行时错误。
这是我的小提琴: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:从字符串“Test string {”到类型“Double”的转换无效。
正在发生。我知道如果我将整数显式转换为字符串,这是一个简单的解决方法:
Console.WriteLine("Test string {" + f.Key.ToString() + "}.")
我只是好奇会发生这种铸造错误的幕后情况。我在代码中的任何地方都没有触及双打,所以我不确定为什么强制转换为“双打”会引发问题。
【问题讨论】: