整理一个复杂的if-else语句

时间:2011-04-20 08:49:33

标签: vb.net if-statement

我正在尝试根据数值找到使用if else语句设置字符串的整洁方法。

唯一的复杂因素是该值可能包含文本。所以它也需要处理这种情况。

所以这是基本代码:

                        If cint(QtyShop) > 0 Then
                            msg = "Stock found in this shop"
                        ElseIf cint(QtyAllShops) > 0 Then
                            msg = "Stock found in a different shop"
                        Else
                            msg= "No stock found anywhere"
                        End If

问题是,如果QtyShop有文本值而不是数字,则会抛出错误。我需要它只是将此场景视为“假”,并继续下一个elseif

目前,我能想到的唯一解决方案是这种丑陋的怪物:

                        If IsNumeric(QtyShop) Then
                            If cint(QtyShop) > 0 Then
                                msg = "Stock found in this shop"
                            ElseIf IsNumeric(QtyAllShops) Then
                                If cint(QtyAllShops) > 0 Then
                                    msg = "Stock found in a different shop"
                                Else
                                    msg = "No stock found anywhere"
                                End If
                            Else
                                msg = "No stock found anywhere"
                            End If
                        Else
                            If IsNumeric(QtyAllShops) Then
                                If cint(QtyAllShops) > 0 Then
                                    msg = "Stock found in a different shop"
                                Else
                                    msg = "No stock found anywhere"
                                End If
                            Else
                                msg = "No stock found anywhere"
                            End If
                        End If

当我看到它时,我感到非常难过。 : - (请有人让它消失。

1 个答案:

答案 0 :(得分:3)

您应该分离业务逻辑的处理(“ 是数量?”)和验证。

首先测试用户输入是否为有效数字。然后将该数字放入数字变量 - 不要处理String变量,就好像它们是数字一样。

启用Option Strict即可让您更轻松。这将导致编译器报告代码中的错误,因为您将字符串视为数字。

最后,考虑提前退货:一旦找到结果就立即返回。这样就可以避免深层嵌套语句:

' Input validation ….

If QtyShop > 0 Then Return "Stock found in this shop"

If QtyAllShops > 0 Then Return "Stock found in a different shop"

Return "No stock found anywhere"