.net – 测试变量的存在性

前端之家收集整理的这篇文章主要介绍了.net – 测试变量的存在性前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我实际上试图检查程序中是否定义了变量.
我是通过使用如下的异常处理技术完成的,

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

解决方法

你可以使用反射:

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

猜你在找的VB相关文章