Select Case on an object's type in VB.NET

2020-05-19 04:21发布

I'm not sure if this valid C#, but hopefully you get the idea. :)

switch (msg.GetType()) {
    case ClassA:
        // blah
    case ClassB:
        // blah 2
    case ClassC:
        // blah 3
}

How would I switch on an object's type but using VB.NET's Select Case?

I'm aware that some might suggest using polymorphism, but I'm using a hierarchy of small message classes so that really wouldn't work in my case.

5条回答
等我变得足够好
2楼-- · 2020-05-19 04:41

With VB 2010, for projects targeting .NET framework 4 and later, you can now do this:

Select Case msg.GetType()
    Case GetType(ClassA)
End Select

In earlier VB versions, it didn't work because you couldn't compare two types with equality. You'd have to check if they point to the same reference using the Is keyword. It's not possible to do this in a Select Case, unless you use a property of the type like the Name or FullName for comparison, as suggested by Michael. You can use a combination of If and ElseIf though:

Dim type = msg.GetType()
If type Is GetType(ClassA)
    ...
ElseIf type Is GetType(ClassB)
    ...
...
End If
查看更多
▲ chillily
3楼-- · 2020-05-19 04:42

This is a way to handle Button1 and Button2 click events in the same sub (I started out as a VB6 programmer, so this is a good substitute for VB6 handling of control arrays)

Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click, Button2.Click
                Select Case True
                    Case sender Is Me.Button1
                        ' Do Button1 stuff '
                    Case sender Is Me.Button2
                        ' Do Button2 stuff '
                End Select
            End Sub
查看更多
叼着烟拽天下
4楼-- · 2020-05-19 04:46

This:

Dim a As Object = New TextBox

Select Case True
    Case TypeOf a Is TextBox
        MsgBox("aaa")

    Case TypeOf a Is ComboBox

    Case TypeOf a Is ListBox

End Select
查看更多
淡お忘
5楼-- · 2020-05-19 04:52

I wouldn't ever select case true, but you can do this:

Select Case msg.GetType.Name
    Case GetType(ClassA).Name
        ...
    Case GetType(ClassB).Name
        ...
    Case Else
        ...
End Select

Which is slighly cleaner looking than this:

If msg.GetType Is GetType(ClassA) Then
    ...
ElseIf msg.GetType Is GetType(ClassB) Then
    ...
Else
    ...
End If
查看更多
狗以群分
6楼-- · 2020-05-19 04:53

Well, if you insist on using Select Case, you could always go with:

Select Case True
    Case TypeOf msg Is ClassA
        ' do something '
    Case TypeOf msg Is ClassB
        ' do something else '
    Case Else
        ' and so on '
End Select

But I would imagine most people like to avoid this kind of thing. If/ElseIf would probably be clearer.

查看更多
登录 后发表回答