Vb.net 在vb中尝试catch语句将字符串转换为double
我有下面的函数,用来检查给定的条目是否高于0.0Vb.net 在vb中尝试catch语句将字符串转换为double,vb.net,Vb.net,我有下面的函数,用来检查给定的条目是否高于0.0 Dim inputstr As String = .Item("conc") Try Dim concentration As Double = CDbl(inputstr) Catch ex As Exception Dim concentration As Double = -1.0 Finally Dim concentration As Double = -1.0 End Try If concentratio
Dim inputstr As String = .Item("conc")
Try
Dim concentration As Double = CDbl(inputstr)
Catch ex As Exception
Dim concentration As Double = -1.0
Finally
Dim concentration As Double = -1.0
End Try
If concentration > 0.0 Then
err = 1
End If
然而,我不断得到“浓度未声明”。由于其保护级别,它可能无法访问
有什么想法吗?谢谢它不在try-catch之外的范围内。在外面声明它,然后尝试在try/catch内设置它。但问题是,由于最后出现了
,,它总是以-1.0
结束
Dim inputstr As String = .Item("conc")
Dim concentration As Double = 0.0
Try
concentration = CDbl(inputstr)
Catch ex As Exception
concentration = -1.0
End Try
If concentration > 0.0 Then
err = 1
End If
最终你可以使用
可变范围
变量Concentration
仅存在于Try块中。因此,无论何时离开该块,该变量都不再存在
要解决此问题,您必须在重试之前声明浓度
最后阻止
您将遇到的另一个问题是,Concentration
始终为-1,因为您在Finally
块中这样说,这里不需要这个块
Dim inputstr As String = .Item("conc")
Dim concentration As Double
Try
concentration = CDbl(inputstr)
Catch ex As Exception
concentration = -1.0
End Try
If concentration > 0.0 Then
err = 1
End If
读一点关于
还有一点关于
不要使用Try/Catch来做这件事
但是,由于您可以使用它来执行此操作,因此它更容易阅读,也更重要
因此,最终,更好的编码实践是:
Dim inputstr As String = .Item("conc")
Dim concentration As Double
If Not Double.TryParse(inputstr, concentration) Then
concentration = -1.0
End If
If concentration > 0.0 Then
err = 1
End If
事实上,您的代码有两个问题
一个浓度
需要在试验前声明
第二步删除最后一步,否则它将始终为-1.0
浓度
不在范围内
最终将始终执行
,不计算是否引发异常-因此浓度
将始终设置为-1.0
-您仍然不需要使用Try..Catch
方法。Double.TryParse
将在一行中处理它
Dim concentration As Double = 0.0
Double.TryParse(.Item("conc"), concentration)
err = If(concentration > 0.0, 1, 0)
Double.TryParse(inputsr,concentration)
-将concentration
设置为转换后的双精度值或默认值,如果字符串格式不正确,则为Double
类型设置为0.0
。如何使用VB.Net,并使用Double.TryParse
或Double.Parse
这将使您的代码类似于
dim concentration as Double = -1
'dont really know where this one is coming from though
err = 0
if Double.TryParse(inputstr, concentration) then
if concentration > 0.0 then
err = 1
end if
end if
它不在try-catch之外的范围内。向外声明它,然后尝试在try/catch内设置它…您不需要try-catch。尝试使用double.TryParse
这似乎是一个。您试图实现的最终目标是什么?所有导致缩进的内容都会创建一个新级别的(块)范围。感谢您的澄清。更改了它。
dim concentration as Double = -1
'dont really know where this one is coming from though
err = 0
if Double.TryParse(inputstr, concentration) then
if concentration > 0.0 then
err = 1
end if
end if