我正在使用visual studio 2008为windows CE 6.0开发软件,紧凑框架。
我有这种“奇怪的?”isNumeric方法有问题。有没有其他更好的方法来做这项工作?为什么让我成为一个例外?(两个在FormatException类型的facts...both中)
谢谢
dim tmpStr as object = "Hello"
if isNumeric(tmpStr) then // EXCEPTIONs on this line
// It's a number
else
// it's a string
end if
发布于 2012-04-05 23:43:46
尽管IsNumeric
的文档中没有列出FormatException
,但它确实是可以抛出的异常之一。抛出它的情况是
0x
或&H
前缀不过,我找不到任何理由来解释这种行为。我能够辨别它的唯一方法就是深入研究reflector中的实现。
解决这个问题的最好方法似乎是定义一个包装器方法
Module Utils
Public Function IsNumericSafe(ByVal o As Object) As Boolean
Try
Return IsNumeric(o)
Catch e As FormatException
Return False
End Try
End Function
End Module
发布于 2012-04-05 23:43:10
出现这个错误的原因实际上是因为CF不包含TryParse
方法。另一种解决方案是使用正则表达式:
Public Function CheckIsNumeric(ByVal inputString As String) As Boolean
Return Regex.IsMatch(inputString, "^[0-9 ]+$")
End Function
编辑
下面是一个更全面的正则表达式,它可以匹配任何类型的数字:
Public Function IsNumeric(value As String) As Object
'bool variable to hold the return value
Dim match As Boolean
'regula expression to match numeric values
Dim pattern As String = "(^[-+]?\d+(,?\d*)*\.?\d*([Ee][-+]\d*)?$)|(^[-+]?\d?(,?\d*)*\.\d+([Ee][-+]\d*)?$)"
'generate new Regulsr Exoression eith the pattern and a couple RegExOptions
Dim regEx As New Regex(pattern, RegexOptions.Compiled Or RegexOptions.IgnoreCase Or RegexOptions.IgnorePatternWhitespace)
'tereny expresson to see if we have a match or not
match = If(regEx.Match(value).Success, True, False)
'return the match value (true or false)
Return match
End Function
有关更多详细信息,请参阅本文:http://www.dreamincode.net/code/snippet2770.htm
https://stackoverflow.com/questions/10031626
复制相似问题