【问题标题】:Behind the scenes of Visual Basic casting - Conversion from string to type 'Double' is not validVisual Basic 强制转换的幕后 - 从字符串到类型“Double”的转换无效
【发布时间】: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() + "}.")

我只是好奇会发生这种铸造错误的幕后情况。我在代码中的任何地方都没有触及双打,所以我不确定为什么强制转换为“双打”会引发问题。

【问题讨论】:

    标签: vb.net string casting


    【解决方案1】:

    VB 中的+ 运算符是一个复杂的野兽。它可以做到非常different things depending on its operands。在您的情况下,它在该表的第三行之后:

    一个表达式是数字数据类型,另一个是字符串

    因此:

    如果 Option StrictOn,则生成编译器错误。

    如果 Option StrictOff,则将 String 隐式转换为 Double 并添加。

    如果 String 无法转换为 Double,则抛出 InvalidCastException 异常。

    看起来Option Strict 在您的代码中必须是Off,因此它确实在尝试将String 转换为Double,因此会出错。

    理想情况下,始终使用Option Strict On(和Option Explicit On - 它们通常是我在使用 VB 时检查的第一件事) - 它会在编译时显示各种潜在的运行时问题。

    另外,如果你想保证字符串连接,Option Strict 与否,你可以使用& operator

    【讨论】:

    • if you want to guarantee string concatenation, Option Strict or not, you can use the & operator 很高兴您在帖子中提到这一点。我不知道这在我工作的地方以及我遇到的一些事情上咬了多少次。很棒的帖子!
    猜你喜欢
    • 2011-07-30
    • 2015-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-06
    • 1970-01-01
    相关资源
    最近更新 更多