嘿,我是在 VB.Net 中使用 Dictionary 的新手,并试图弄清楚如何使用 try catch 来检查输入的正确变量类型以及空条目除外。我感到困惑的困难部分是为用户合并错误处理消息。我希望在 catch 中输出每个不正确的键和变量。
例如
Dim dblTravel = New Dictionary(Of String, Double)
dblTravel.Add("Travel_Days", CDbl(txtTravelDays.Text))
dblTravel.Add("Private_Vehicle_Miles", CDbl(txtPrivateVehicleMiles.Text))
dblTravel.Add("Lodging_Per_Night", CDbl(txtLodgingPerNight.Text))
dblTravel.Add("Travel_Total", Nothing)
Dim dblExpenses = New Dictionary(Of String, Double)
dblExpenses.Add("Airfare", CDbl(txtAirfare.Text))
dblExpenses.Add("Car_Rental_Fees", CDbl(txtCarRentalFees.Text))
dblExpenses.Add("Parking_Fees", CDbl(txtParkingFees.Text))
dblExpenses.Add("Taxi_Charges", CDbl(txtTaxiCharges.Text))
dblExpenses.Add("Registration_Fees", CDbl(txtRegistationFees.Text))
dblExpenses.Add("Meals", CDbl(txtMeals.Text))
这是我的两个字典变量,它们有自己的索引键。我想将 try catch 合并在一起,并且对于每个不在正确数据类型或空值中的键值类型,我想将它输出到用户的错误消息中。
输出示例
这些类型的错误应该被记录并显示在用户的错误处理消息中。示例输出中的那些是输出显示的示例以及我要检查的两个错误。
提前感谢您的浏览,希望您能提供帮助。
最佳答案
Try/Catch
对于基本数据验证来说有点矫枉过正。当您无法预见可能出现的问题时使用它 - 您已经给出了用户输入应遵循的规则,因此您知道要检查什么。
假设一些 button_ok 点击事件:
Sub ok_click(....)
Dim travelDays As Integer ' double is overkill too
Dim AirFare as Decimal ' Decimal is better than Double for Money
Dim TaxiFare as Decimal
If Integer.TryParse(tbTravelDays.Text, travelDays) = False Then
' the contents of the control cannot be converted to a integer value.
' complain to user; MessageBox.Show then
Exit Sub
Else
' the TryParse passed, so travelDays is a valid integer
' you might also want to check that it is not negative!
End If
If Decimal.TryParse(tbTaxi.Text, TaxiFare ) = False Then
' the contents of the control cannot be converted to a decimal value.
' complain to user; MessageBox.Show then
Exit Sub
Else
' passes too
' your "not empty" rule probably means they have to enter a number,
End If
如果一切顺利(数据验证),这些变量将具有它们输入的值。所以接下来:
' procedure to recieve the values and add them
AddValuesToDictionary(travelDays, AirFare, TaxiFare)
您将不得不稍微摆弄一下-您的 Dictionary 当前是 (string, Double),我会将其转换为 Decimal,唯一的奇怪之处是
TravelDays
可能是 Integer
。您知道您的字典将为任何键(如“TravelDays”)保留一 (1) 个条目吗?如果您试图为多个员工收集值(value),每个员工都有自己的差旅费用,它会爆炸。
关于vb.net - 尝试使用 Catch 显示输入错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26742397/