我在表格中有一系列文本框来收集输入,如下所示:
用户将为他们需要的每个测量点输入目标值和实际值。然后,我想根据公差文本框中输入的公差,根据目标值验证实际值。输入的所有测量点的公差都相同,但用户不会总是输入所有10个测量点。
我还创建了一个非常基本的类,其中包含一个接受目标,实际和容差值的函数,然后根据实际值是否在容差范围内返回布尔值。我意识到我可以使用这个if语句的ruck加载来检查每个文本框的输入然后使用类来执行验证,但是这似乎是很多代码重复和有点粗糙。我的问题是有更好的方法可以执行此验证吗?
编辑课程内容
Public Class TolerenceHelper
Public Function IsInTolerence(ByVal target As Integer, ByVal actual As Integer, ByVal tolerence As Integer) As Boolean
Dim upper As Integer = target + tolerence
Dim lower As Integer = target - tolerence
If actual < lower OrElse actual > upper Then
Return False
Else
Return True
End If
End Function
调用如下函数:
Dim m1 As TolerenceHelper
Dim flag As Boolean = True
m1 = New TolerenceHelper
If m1.IsInTolerence(Integer.Parse(txtT1.Text), Integer.Parse(txtA1.Text), Integer.Parse(txtTolerance.Text)) = False Then
flag = False
End If
If flag = False Then
lblTest.Text = "Out of tolerance"
Else
lblTest.Text = "In tolerance"
End If
答案 0 :(得分:1)
您的帮助方法似乎没问题,但您没有展示您想要改进的重要部分。加载所有文本框并检查它们是否有效的部分。
以下是使用自定义类Measurement
的方法。你可以使用
Math.Abs(target.Value - actual.Value) <= tolerance
根据目标和容差确定值是否有效。
Public Class Measurement
Public Property Tolerance As Int32
Public Property Target As Int32
Public Property Value As Int32
Public ReadOnly Property IsValid As Boolean
Get
Return Math.Abs(Target - Value) <= Tolerance
End Get
End Property
End Class
我会将所有文本框添加到同一容器控件中,如Panel
。然后,您可以使用Enumerable.OfType
查找相关的文本框。我使用Enumerable.Zip
将值和目标放在一起。使用Int32.TryParse
验证文字。
Dim tolerance As Int32
If Not Int32.TryParse(txtTolerance.Text, tolerance) Then
lblTest.Text = "Enter a valid tolerance! Tolerance must be a positive integer(incl. zero)."
Return
End If
Dim value As Int32
Dim allTxtTarget = From txt In Me.PnlMeasurement.Controls.OfType(Of TextBox)()
Where txt.ID Like "txtT#*" AndAlso Int32.TryParse(txt.Text, value)
Let x = New With {.TextBox = txt, .Value = value, .Type = "Target", .Number = txt.ID.Substring(4)}
Order By x.Number
Select x
Dim allTxtActual = From txt In Me.PnlMeasurement.Controls.OfType(Of TextBox)()
Where txt.ID Like "txtA#*" AndAlso Int32.TryParse(txt.Text, value)
Let x = New With {.TextBox = txt, .Value = value, .Type = "Value", .Number = txt.ID.Substring(4)}
Order By x.Number
Select x
Dim allMeasurements = allTxtTarget.Zip(allTxtActual,
Function(target, actual) New Measurement With {
.Tolerance = tolerance,
.Target = target.Value,
.Value = actual.Value
}).ToList()
输出结果:
For i As Int32 = 0 To allMeasurements.Count - 1
Dim m = allMeasurements(i)
Console.WriteLine("Measurement {0}: Tolerance:{1} Target:{2} Value:{3} Valid:{4}",
i+1, tolerance, m.Target, m.Value, m.IsValid)
Next
如果您确实需要检查所有或至少一个测量是否有效,您可以使用:
Dim allValid = allMeasurements.All(Function(m) m.IsValid)
Dim anyValid = allMeasurements.Any(Function(m) m.IsValid)
或找到最高有效测量值:
Dim validMeasurements = From m In allMeasurements
Where m.IsValid
Order By m.Value Descending
Dim highestMeasurement = validMeasurements.FirstOrDefault()