测试变量的存在性

时间:2013-10-16 06:18:13

标签: .net vb.net

我实际上试图检查程序中是否定义了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

3 个答案:

答案 0 :(得分:7)

您可以使用反射:

Return AnObject.GetType().GetProperty("TestVar") IsNot Nothing

答案 1 :(得分: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

答案 2 :(得分:0)

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

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的评论)是可行的方法。