什么方法可以使这段代码更有效率或更合适?

时间:2017-04-09 22:42:22

标签: vb.net visual-studio-2017

我有一个程序可以根据选中的单选按钮收集信息,还有一个复选框。

Private Sub calculateBtn_Click(sender As Object, e As EventArgs) Handles calculateBtn.Click
    Dim TypeCost As Integer
    Dim ColorCost As Integer
    Dim Foldable As Integer

    If standardRbtn.Checked() Then
        TypeCost = 99
    End If
    If deluxRbtn.Checked() Then
        TypeCost = 129
    End If
    If premiumRbtn.Checked() Then
        TypeCost = 179
    End If

    If blueRbtn.Checked() Then
        ColorCost = 0
    End If
    If redRbtn.Checked() Then
        ColorCost = 10
    End If
    If pinkRbtn.Checked() Then
        ColorCost = 15
    End If

    If foldableCheckBox.Checked() Then
        Foldable = 25
    Else
        Foldable = 0
    End If

    Dim Price As String = TypeCost + ColorCost + Foldable

    priceTextBox.Text() = "$" & Price
End Sub

我强烈感觉这段代码可以简化,但我似乎无法想到它是什么。我的朋友建议使用Enumerations和Arrays,但我不认为那些会起作用。他们会吗?

我一直在寻找与此类似的问题。

我还想指出,类型单选按钮和彩色单选按钮位于不同的组框中,因此它们分别起作用。使得不可能同时选择多种类型或颜色。

我已将代码提升为:

If standardRbtn.Checked() Then
        TypeCost = 99
    ElseIf deluxRbtn.Checked() Then
        TypeCost = 129
    ElseIf premiumRbtn.Checked() Then
        TypeCost = 179
    End If

    If blueRbtn.Checked() Then
        ColorCost = 0
    ElseIf redRbtn.Checked() Then
        ColorCost = 10
    ElseIf pinkRbtn.Checked() Then
        ColorCost = 15
    End If

    If foldableCheckBox.Checked() Then
        Foldable = 25
    Else
        Foldable = 0
    End If

我知道有一些非常简单的事情可以解决一些重复问题。谢谢你,phatfingers。

如果有任何其他想法想要抛弃,我很乐意听到。但这个解决方案对我来说已经足够了。

2 个答案:

答案 0 :(得分:0)

I simply went from using a bunch of if statements to "ElseIf". The updated code is in the original thread. :) - Thank you to phatfingers for the idea.

答案 1 :(得分:0)

You could use a dropdown, which would probably be the lowest effort solution and allow you to dynamically add new options without rewriting anything.

You can then just fetch the value of the selected item.

https://forums.asp.net/t/988528.aspx?Dynamically+adding+items+in+DropDownList

So something like:

Private Sub OnFormLoad() //I forgot the exact name of the load event of the form and what it looks like

    typeDropDown.Items.Add(New ListItem("Standard", "99"))
    typeDropDown.Items.Add(New ListItem("Premium", "129"))
    typeDropDown.Items.Add(New ListItem("Deluxe", "179"))

    colorDropDown.Items.Add(New ListItem("Blue", "0"))
    colorDropDown.Items.Add(New ListItem("Red", "10"))
    colorDropDown.Items.Add(New ListItem("Pink", "15"))
End Sub

Private Sub calculateBtn_Click(sender As Object, e As EventArgs) Handles calculateBtn.Click
     Dim Price as String = typeDropDown.SelectedValue + _
         colorDropDown.SelectedValue + _
         iif(foldableCheckBox.Checked(), 25, 0)
     priceTextBox.Text() = "$" & Price
End Sub