我正在寻找可以简化一系列子程序以最小化重复代码的方法

时间:2014-09-04 03:15:47

标签: vb.net

我有一系列的剪辑,我有50多个,但它们并没有那么不同。是否有更简单或更少线路消费的版本?下面的代码(我总共有60个这样的场景):它们是隐形按钮FYI,它们点击......是的..我知道。 拉出的数据用于各种原因。谢谢,抱歉。

Private Sub Alabama_Click(sender As Object, e As EventArgs) Handles Alabama.Click
    SelectedStateOverviewLabel.Text = "Alabama"
    StateTwoDigit.Text = "AL"
    StateInitials = "AL"
    Call StateClick()
End Sub 'Alabama
Private Sub Alaska_Click(sender As Object, e As EventArgs) Handles Alaska.Click
    SelectedStateOverviewLabel.Text = "Alaska"
    StateTwoDigit.Text = "AK"
    StateInitials = "AK"
    Call StateClick()
End Sub 'Alaska
Private Sub Arizona_Click(sender As Object, e As EventArgs) Handles Arizona.Click
    SelectedStateOverviewLabel.Text = "Arizona"
    StateTwoDigit.Text = "AZ"
    StateInitials = "AZ"
    Call StateClick()
End Sub 'Arizona

1 个答案:

答案 0 :(得分:0)

是的,对于常见代码,您应该创建一个公共例程并传入参数:

Private Sub UpdateState(stateName as string, stateCode as string)
    SelectedStateOverviewLabel.Text = stateName
    StateTwoDigit.Text = stateCode
    StateInitials = stateCode
End Sub

然后您可以按如下方式调用此例程:

Private Sub Alabama_Click(sender As Object, e As EventArgs) Handles Alabama.Click
    UpdateState("Alabama","AL")
    StateClick()
End Sub 'Alabama
Private Sub Alaska_Click(sender As Object, e As EventArgs) Handles Alaska.Click
    UpdateState("Alaska","AK")
    StateClick()
End Sub 'Alaska
Private Sub Arizona_Click(sender As Object, e As EventArgs) Handles Arizona.Click
    UpdateState("Arizona","AZ")
    StateClick()
End Sub 'Arizona

但是你应该考虑将状态存储在HashTable中并使用枚举作为名称,但这超出了这个问题的范围