【问题标题】:What is the VB equivalent of Java's instanceof and isInstance()?Java 的 instanceof 和 isInstance() 的 VB 等价物是什么?
【发布时间】:2009-06-16 23:56:39
【问题描述】:

本着c# 问题的精神..

在 VB.NET 中比较类类型的等效语句是什么?

【问题讨论】:

    标签: java vb.net reflection introspection instanceof


    【解决方案1】:

    您是否正在寻找类似TypeOf 的内容?这仅适用于引用类型,不适用于 int/etc。

    If TypeOf "value" Is String Then
         Console.WriteLine("'tis a string, m'lord!")
    

    或者你想比较两个不同的变量实例?也适用于 ref 类型:

    Dim one As Object = "not an object"
    Dim two As Object = "also not an object, exactly"
    Dim three as Object = 3D
    
    If one.GetType.Equals( two.GetType ) Then WL("They are the same, man")
    If one.GetType Is two.GetType then WL("Also the same")
    If one.GetType IsNot three.GetType Then WL("but these aren't")
    

    如果您不使用两个对象,您也可以像这样使用gettype():

    If three.GetType Is gettype(integer) then WL("is int")
    

    如果您想查看某个东西是否是另一种类型的子类(并且在 .net 3.5 中):

    If three.GetType.IsSubclassOf(gettype(Object)) then WL("it is")
    

    但如果你想在早期版本中这样做,你必须翻转它(看起来很奇怪)并使用:

    If gettype(Object).IsAssignableFrom(three.GetType) Then WL("it is")
    

    所有这些都在SnippetCompiler 中编译,所以如果你没有它,那就去 DL。

    【讨论】:

      【解决方案2】:
      TypeOf obj Is MyClass
      

      【讨论】:

        【解决方案3】:

        与您的链接问题等效的 VB 几乎相同:

        Dim result As Boolean = obj.GetType().IsAssignableFrom(otherObj.GetType())
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2010-09-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多