在 VB.NET 中选择对象类型的大小写 [英] Select Case on an object's type in VB.NET

查看:34
本文介绍了在 VB.NET 中选择对象类型的大小写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定这个 C# 是否有效,但希望你能理解.:)

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
}

如何打开对象的类型但使用 VB.NET 的 Select Case?

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.

推荐答案

借助 VB 2010,对于面向 .NET Framework 4 及更高版本的项目,您现在可以执行以下操作:

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

在早期的 VB 版本中,它不起作用,因为您无法相等地比较两种类型.您必须使用 Is 关键字检查它们是否指向相同的引用.在 Select Case 中不可能这样做,除非您使用 Name 或 FullName 等类型的属性进行比较,如 Michael 所建议的.不过,您可以结合使用 If 和 ElseIf:

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

这篇关于在 VB.NET 中选择对象类型的大小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆