我正在尝试使用select case语句验证数据范围。我遇到了其他嵌套选择案例的问题。这是可能的还是我愿意思考?或者我应该将选择案例陈述分开堆叠?
例如,这是我在vb中的代码:
Select Case intyear
Case 2000 To 2025
Select Case intmonth
Case 1 To 12
BlnDateValid = True
End Select
Select Case intDay
Case 1 To 31
BlnDateValid = True
End Select
Select Case intHours
Case 0 To 23
BlnDateValid = True
End Select
Select Case intAddDays
Case 0 To 60
BlnDateValid = True
End Select
Select Case intAddHours
Case 0 To 23
BlnDateValid = True
End Select
Case Else
BlnDateValid = False
End Select
If blnDatevalid = false then
MessagebBox.Show("Please check all fields and enter valid
data", "Invalid data", MessageBoxButtons.OK)
不幸的是,缩进的意义并没有帮助代码有意义。 Select Case
的重点是整齐地选择多个案例中的一个。有一个案例的Select Case
是错误的代码,你应该使用If
语句。在这种情况下,您应该特别使用If
语句,因为您可以使用单个Select Case
语句替换所有这些If
语句。
If Not (intyear >= 2000 AndAlso intyear <= 2025 AndAlso
intmonth >= 1 AndAlso intmonth <= 12 AndAlso
intDay >= 1 AndAlso intDay <= 31 AndAlso
intHours >= 0 AndAlso intHours <= 23 AndAlso
intAddDays >= 0 AndAlso intAddDays <= 60 AndAlso
intAddHours >= 0 AndAlso intAddHours <= 23) Then
MessagebBox.Show("Please check all fields and enter valid data", "Invalid data", MessageBoxButtons.OK)
End If
所有Select
或If
检查仍然会让你容易受到像2月30日那样的非感性值。更好的是真正尝试创造一个DateTime
值。
Dim d As DateTime
Dim t As TimeSpan
Try
d = New DateTime(intYear, intMonth, intDay, intHours, 0, 0)
t = New TimeSpan(intAddDays, intAddHours, 0, 0)
If t > (New TimeSpan(60, 23, 0, 0)) Then Throw New ArgumentOutOfRangeException()
Catch
MessagebBox.Show("Please check all fields and enter valid data", "Invalid data", MessageBoxButtons.OK)
End Try
或者您可以创建一个字符串并尝试解析它:
If Not DateTime.TryParse($"{intYear}-{intMonth}-{intDay} {intHours}:00:00")
MessagebBox.Show("Please check all fields and enter valid data", "Invalid data", MessageBoxButtons.OK)
End If