测试变量的存在性

Raj*_*amy 3 .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
Run Code Online (Sandbox Code Playgroud)

是否有任何简单的解决方案可以实现这一目标.或者这很好实施.

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

if(TypeOf Testvar === "undefined") { ... }
Run Code Online (Sandbox Code Playgroud)

在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 
Run Code Online (Sandbox Code Playgroud)

补充说明:

@Damien_The_Unbeliever解决方案返回Nothing尽管具有该成员的已铸造对象.

'Evaluated by using the above case i given
 ?xObj.GetType().GetProperty("xAnotherVar")
 Nothing
Run Code Online (Sandbox Code Playgroud)

Dam*_*ver 7

你可以使用反射:

Return AnObject.GetType().GetProperty("TestVar") IsNot Nothing
Run Code Online (Sandbox Code Playgroud)

  • @RajaPrabhuOfficial:你似乎已经宣布`TestVar`只是一个字段而不是属性.因此,请尝试使用[`GetField`](http://msdn.microsoft.com/en-us/library/53seyfee.aspx)而不是[`GetProperty`](http://msdn.microsoft.com/en -us /库/ kz0a8sxy.aspx). (2认同)