我正在完成一项任务。它已经完成,但我想找到更有效的方法在未来的项目中使用布尔值。
我有多个功能需要验证。我尝试参数没有成功,不得不为每个函数创建单独的布尔值。
我的代码是
Function valChargeParts() As Boolean
Try
If Decimal.TryParse(CDec(txtParts.Text), 1) Then
If CDec(txtParts.Text) >= 0 Then
Return True
End If
End If
Catch ex As Exception
End Try
Return False
End Function
Function valChargeLabor() As Boolean
Try
If Decimal.TryParse(CDec(txtLabor.Text), 1) Then
If CDec(txtLabor.Text) >= 0 Then
Return True
End If
End If
Catch ex As Exception
End Try
Return False
End Function
Function CalcPartsCharges() As Decimal
Dim totalParts As Integer = 0
If valChargeParts() = True Then
totalParts += CDec(txtParts.Text)
End If
Return totalParts
End Function
Function CalcLaborCharges() As Decimal
Dim totalLabor As Integer = 20
If valChargeLabor() = True Then
totalLabor *= CDec(txtLabor.Text)
End If
Return totalLabor
End Function
我尝试了许多可能的方法来创建参数,例如;
Function valChargeLabor(ByVal variable as Decimal) As Boolean
并尝试在函数中使用
If Decimal.TryParse(variable, 1) Then
但没有效果。我不确定我做错了什么。
提前致谢。
答案 0 :(得分:1)
试试这个
Function IsValidDecimal(ByVal txt As String) As Boolean
Try
Dim t As Decimal = 0
If Decimal.TryParse(txt, t) Then
If t >= 0 Then
Return True
End If
End If
Catch ex As Exception
End Try
Return False
End Function
Function CalcPartsCharges() As Decimal
If Me.IsValidDecimal(Me.txtParts.Text) Then Return CDec(Me.txtParts.Text)
Return 0
End Function
Function CalcLaborCharges() As Decimal
If Me.IsValidDecimal(Me.txtLabor.Text) Then Return CDec(Me.txtLabor.Text) * 20
Return 0
End Function
或者只是
Function GetDecimal(ByVal txt As String) As Decimal
Dim t As Decimal = 0
Try
If Not Decimal.TryParse(txt, t) Then Return 0
If t < 0 Then t = 0
Catch ex As Exception
End Try
Return t
End Function
Function CalcPartsCharges() As Decimal
Return Me.GetDecimal(Me.txtParts.Text)
End Function
Function CalcLaborCharges() As Decimal
Return Me.GetDecimal(Me.txtLabor.Text) * 20
End Function
答案 1 :(得分:1)
查看你的代码,你正在使用TryParse方法,如果它不能转换,它不会给你一个错误,而且你使用多个转换为十进制,我认为不需要。我做了一个常见的例程,它返回一个布尔值,如果它可以转换加上它将通过引用传递实际的转换值,所以它将使它像你自己的TryParse语句。
这是一个简单的修改应用程序来演示我在说什么。
Public Class Form1
Dim totalParts As Decimal = 0
Function validateInput(value As String, ByRef output As Decimal) As Boolean
Return Decimal.TryParse(value, output)
End Function
Function CalcPartsCharges() As Decimal
Dim tempParts As Decimal = 0
If validateInput(txtParts.Text, tempParts) Then
totalParts += tempParts
End If
Return totalParts
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Label1.Text = CalcPartsCharges().ToString()
End Sub
End Class