好吧,在投票(类型为“booo just read the documentation -1”)和对评论的猜测之后,我想我必须寻找一个好的答案。
这是执行Val
http://referencesource.microsoft.com/#Microsoft.VisualBasic/Conversion.vb,6492d8e784d2ae91
问题从这里开始:
ch = InputStr.Chars(i)
If ch = "&"c Then 'We are dealing with hex or octal numbers
Return HexOrOctValue(InputStr, i + 1)
只要第一个非空格字符(ch
)是这样&
调用的HexOrOctValue
HexOrOctValue(InputStr, i + 1)
检查 HexOrOctValue .net 实现:
http ://referencesource.microsoft.com/#Microsoft.VisualBasic/Conversion.vb,41d686eb6be390d9
第二个参数(像i+1
from一样Val
传递)用作.InputStr
i+1
当然,如果i
是最后一个字符的索引,则不会有索引。所以HexOrOctValue
会在这一行触发这个错误ch = InputStr.Chars(i) // i here has the Vals' i+1 value
这就是为什么Dim test As Integer = Val(" &")
会产生索引超出范围错误......因此Dim test As Integer = Val(" & ")
不会产生错误(已验证)。
修复?这取决于你的口味。我认为侵入性较小的方式是一个包装器,它只是添加一个额外的字符来确保总是有一个i+1
索引:
Public Function myVal(ByVal InputStr As String) As Double
Return Val(InputStr + " ")
End Function
好吧,通过这种方式,“错误”在某种程度上被隐藏在了地毯下,这不是绝对严格定义的“最佳”实践,但它足够小,可以批准并让事情继续下去。
ps "&" 是唯一受此错误影响的字符。