最近,我在编程课程(VB教学)中一直在报道数据类型,我遇到了一个有趣的情况。在尝试演示随机数生成器时,我遇到了这样一个事实:我的代码允许在算术语句中清晰地使用字符串。虽然我很喜欢这样做,但是我正在为了理由或实际导致这种情况发生的事情而震撼我的大脑。
下面是我为测试这个而构建的一些代码的一些示例:
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'Produces '56'
MsgBox("5" + "6")
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
'Produces 11
MsgBox(5 + 6)
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
'Produces 11
MsgBox("5" + 6)
End Sub
Private Sub RandomNumber(ByVal low As Integer, ByVal high As Integer)
Randomize()
MsgBox((high - low) * Rnd() + low)
End Sub
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
'Produces Random Number between 5 - 6
RandomNumber(5, "6")
End Sub
Private Sub Button6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button6.Click
'Produces Random Number between 5 - 6
RandomNumber("5", "6")
End Sub
Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click
'Produces Random Number between 5 - 6
RandomNumber(5, 6)
End Sub
End Class
如果它是IDE的东西,我在Windows 7上使用Visual Studio 2010 Ultimate。
答案 0 :(得分:2)
我猜你有Option Strict设置为Off。
查看MSDN(http://msdn.microsoft.com/en-us/library/9c5t70w2.aspx)中有关+运算符的文档:
“一个表达式是数字数据类型,另一个是字符串
如果Option Strict为On,则生成编译器错误。 如果Option Strict为Off,则隐式将String转换为Double并添加。 如果String无法转换为Double,则抛出InvalidCastException异常。“