是否可以使用较少的冗余来执行此代码?

时间:2015-01-26 15:42:10

标签: vb.net refactoring

我有以下代码:

If moves.Contains("1") Then
    lblOnes.Visible = True
End If

If moves.Contains("2") Then
    lblTwos.Visible = True
End If

If moves.Contains("3") Then
    lblThrees.Visible = True
End If

If moves.Contains("4") Then
    lblFours.Visible = True
End If

If moves.Contains("5") Then
    lblFives.Visible = True
End If

If moves.Contains("6") Then
    lblSixes.Visible = True
End If

我只觉得它是多余的,有没有办法做到这一点,而不是一遍又一遍地重复相同的陈述?

4 个答案:

答案 0 :(得分:4)

你可以,例如使用Dictionary

进行查找
Dim map = new Dictionary(Of String, Label) From
{
    {"2", lblTwos},
    {"3", lblThrees},
    {"4", lblFours},
    {"5", lblFives},
    {"6", lblSixes}
}

For Each kvp In map
    If moves.Contains(kvp.Key) Then
        kvp.value.Visible = True
    End If 
Next

其他可能的方式:

  • 使用控件的Tag属性
  • 为您的控件lbl_1lbl_2等命名并循环遍历moves中的所有元素,以便按名称查找正确的控件。

答案 1 :(得分:2)

另一个例子:

    Dim lbls() As Label = {lblOnes, lblTwos, lblThrees, lblFours, lblFives, lblSixes}
    For i As Integer = 0 To lbls.Length - 1
        If moves.Contains((i + 1).ToString) Then
            lbls(i).Visible = True
        Else
            ' ... possibly do something in here? ...
        End If
    Next

答案 2 :(得分:0)

如果您可以将标签从lblOnes,lblTwos等重命名为lbl1s,lbl2s,那么它只会是:

For i = 1 To 6
    Me.Controls("lbl" & i & "s").Visible = moves.Contains(i.ToString())
Next

答案 3 :(得分:0)

我提出以下想法:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        Dim moves As String
        moves = "1"
        Dim controlName As String
        controlName = "lbl" + moves
        CType(Me.Controls("controlName"), Label).Visible = True
    End Sub