3

我实际上试图检查variable程序中是否定义了一个。我是通过使用exception handling下面的技术完成的,

private sub IsTestVarDefined() as boolean
  try
   dim xDummy = AnObject.TestVar  'Where AnObject is using the type Object
   return true
  catch
   return false
  end try
end sub

是否有任何简单的解决方案可以实现这一目标。?或者这可以实施吗?

如果我正在使用 javascript 编程,那么我会这样做,

if(TypeOf Testvar === "undefined") { ... }

我一直在寻找与上述非常相似的方法,在 vb.net 中。

我的案例的示例图片:

Public Class Class1
 public Dim xVar as integer = 0
End Class 

Public Class Class2
 public Dim xAnotherVar as integer = 0
End Class 

Public Class SomeOtherClass
 Dim xObj as Object  = New Class2
 'Now i want to check whether the xObj is having xVar or Not?
End Class 

补充说明:

@Damien_The_Unbeliever 解决方案返回 Nothing 即使铸造对象具有该成员。

'Evaluated by using the above case i given
 ?xObj.GetType().GetProperty("xAnotherVar")
 Nothing
4

3 回答 3

8

您可以使用反射:

Return AnObject.GetType().GetProperty("TestVar") IsNot Nothing
于 2013-10-16T06:28:01.730 回答
0

将其提升为属性并在接口中定义它不是比尝试使用反射更合适吗?那么你可以将你的对象强制转换为接口类型,并以强类型的方式处理吗?

Sub Main()
    Dim horsie As Object = New Horse()
    Dim cart As Object = New Cart()

    Dim ihorsie As IMyVal = TryCast(horsie, IMyVal)
    Dim icart As IMyVal = TryCast(cart, IMyVal)

    Console.WriteLine("horsie has myVal (Interface): " & (ihorsie IsNot Nothing))
    'true
    Console.WriteLine("cart has myVal (Interface): " & (icart IsNot Nothing))
    'false
End Sub

Public Interface IMyVal
    Property myVal() As Integer
End Interface

Public Class Horse
    Implements IMyVal
    Public Property myVal() As Integer Implements IMyVal.myVal
        Get
            Return m_myVal
        End Get
        Set(value As Integer)
            m_myVal = value
        End Set
    End Property
    Private m_myVal As Integer
End Class

Public Class Cart

End Class

如果您必须将其用作变量并使用反射来查找它,那么 Damien_The_Unbeliever 的响应(以及随后关于 GetField 的评论)是您的最佳选择。

于 2013-10-16T08:41:10.690 回答
0

只需 3 行代码就可以完成这项工作:

private sub IsTestVarDefined() as boolean
   return Not AnObject Is Nothing
end sub

以及是否要测试是否定义了变量(但变量必须是引用类型)

private sub IsTestVarDefined() as boolean 
   if AnObject Is Nothing OrElse AnObject.TestVar is Nothing
      return false
   else
       return true
end sub
于 2013-10-16T06:22:13.937 回答