问题
Recently, I've been covering data types in my programming course (teaching VB) and I've run into an interesting situation. While attempting to demonstrate a random number generator, I ran into the fact that my code was allowing for Strings to be used legibly in arithmetic statements. While I'm fine with it doing it, I'm wracking my brain as to the justification or the what is actually causing this to happen.
Below are some examples of some code I built to test this:
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
In case it is an IDE thing, I'm using Visual Studio 2010 Ultimate on Windows 7.
回答1:
I'm guessing you have Option Strict set to Off.
Check out the documentation from MSDN (http://msdn.microsoft.com/en-us/library/9c5t70w2.aspx) for the + operator:
"One expression is a numeric data type and the other is a string
If Option Strict is On, then generate a compiler error. If Option Strict is Off, then implicitly convert the String to Double and add. If the String cannot be converted to Double, then throw an InvalidCastException exception."
来源:https://stackoverflow.com/questions/19150375/why-does-visual-basic-allow-strings-to-be-added-to-integers-in-arithmetic-statem