Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

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

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.

question from:https://stackoverflow.com/questions/1301881/select-case-on-an-objects-type-in-vb-net

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...