可以在VB.NET的Select ... Case中使用控件作为switch变量吗?

时间:2012-03-27 13:50:14

标签: vb.net

我正在处理一个函数,该函数处理来自多个按钮的事件,并尝试根据单击的按钮定义Select ... Case。像这样......

   Private Sub btnClick(ByVal sender As System.Object, ByVal e As System.EventArgs) _
        Handles btnThis.Click, _
                btnThat.Click, _
                btnTheOther.Click
        Dim button_clicked As Button = CType(sender, Button)

        ...Do some common parts...

        Select button_clicked

            Case btnThis
                 ...Do this...

            Case btnThat
                 ...Do that...

            Case btnTheOther
                 ...Do the other...

            Case Else

        End Select

但我无法编译;它报告“操作符=未定义类型'System.Windows.Forms.Button'和'System.Windows.Forms.Button'”。我也试过了

Select button_clicked

    Case btnThis.Equals

Select button_clicked

    Case btnThis.Equals(button_clicked)

哪个也不起作用。有没有办法以这种方式定义Select ... Case,或者由于尝试比较引用类型而总是注定要失败?

3 个答案:

答案 0 :(得分:3)

您必须使用Is关键字来比较对象是否相等,但您必须使用If语句进行检查。

If sender Is btnThis Then
     ...
ElseIf sender Is btnThat Then
     ...
End If

答案 1 :(得分:2)

使用控件的名称是一个选项:

Private Sub btnClick(ByVal sender As Object, ByVal e As EventArgs) _
            Handles btnThis.Click, _
                    btnThat.Click, _
                    btnTheOther.Click

  Select DirectCast(sender, Button).Name
    Case btnThis.Name
      ...do this...
    Case btnThat.Name
      ...do that...
    Case btnTheOther.Name
      ...do the other...
    Case Else
      ...etc
  End Select
End Sub

答案 2 :(得分:1)

Select Case True
    Case sender Is Button1
        MsgBox("Button One!")
    Case sender Is Button2
        MsgBox("Button Two!")
End Select