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

Is it possible to do this code with less redundancy?

我有以下代码:

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

我只是觉得它是多余的,有什么方法可以做到这一点而不用一遍又一遍地重复同样的语句吗?

你可以,例如使用 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 中的所有元素以通过其名称找到正确的控件。

如果您有幸将标签从 lblOnes、lblTwos 等重命名为 lbl1s、lbl2s,那么它将只是:

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

另一个例子:

    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

我提出以下想法:

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