如何使用本机方法将字符串转换为使用默认值的double?
这样的东西?
dim value as double
dim text
value = Double.TryParse(text, 0)
答案 0 :(得分:3)
Dim text As String = "123.45"
Dim value As Double
If Double.TryParse(text, value) Then
' text is convertible to Double, and value contains the Double value now
Else
' Cannot convert text to Double set the default value here
End If
答案 1 :(得分:3)
这应该在一行中完成:
Dim value as Double
Dim text="23.675"
If Not Double.TryParse(text, value) Then value = 4
'At this point value contains either the parsed value of text
'or 4 if text couldn't be parsed into a double
文档:http://msdn.microsoft.com/en-us/library/994c0zb1(v=vs.110).aspx
您当然可以使用默认值创建一个方法:
Public Function TryParseDoubleDefault(text as String, defaultValue as Double) As Double
Dim parsedValue As Double
If Not Double.TryParse(text, parsedValue) Then parsedValue = defaultValue
Return parsedValue
End Function
你甚至可以将它作为Double的扩展方法:
<Extension()>
Public Function TryParseDefault(aDouble As Double, text as String, defaultValue as Double) As Double
Dim parsedValue As Double
If Not Double.TryParse(text, parsedValue) Then parsedValue = defaultValue
Return parsedValue
End Function
这样你就可以按照原来的要求做到这一点:
value = Double.TryParseDefault(text, 4)