2014-01-10 6 views

ответ

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 

Docs: 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) 
+0

Если вам нужно это много, писать расширения. – Alexander

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 
Смежные вопросы