-3

为什么val("&")给出IndexOutOfRangeException(Index was outside the bounds of the array.) ?

它不应该只返回零吗?

对此是否有“修复”,因此它将返回零?我已经有很多val(something)分散在整个项目中,我不想到处添加if (something<>"&") Then....

另外,是否有更多的字符在使用时会产生这种错误val()


示例代码 Dim test As Integer = Val("&")

ps 我可以编写一个带有检查的包装器“myVal”函数,if (something<>"&") Then 但我想知道是什么导致了这个问题,所以我可以有一个可靠的修复。

4

1 回答 1

2

好吧,在投票(类型为“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)是这样&调用的HexOrOctValueHexOrOctValue(InputStr, i + 1)

检查 HexOrOctValue .net 实现: http ://referencesource.microsoft.com/#Microsoft.VisualBasic/Conversion.vb,41d686eb6be390d9

第二个参数(像i+1from一样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 "&" 是唯一受此错误影响的字符。

于 2015-03-10T11:49:41.843 回答