.net 测试一个变量';存在
实际上,我试图检查程序中是否定义了.net 测试一个变量';存在,.net,vb.net,.net,Vb.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 有什么简单的解决方案可以实现这一点吗。?或者这是罚款执行 如果我
变量。
我使用了异常处理
技术,如下所示
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
附加说明:
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_不信者解决方案不返回任何内容,即使铸造对象具有该成员
'Evaluated by using the above case i given
?xObj.GetType().GetProperty("xAnotherVar")
Nothing
只需3行代码即可完成此任务:
private sub IsTestVarDefined() as boolean
return Not AnObject Is Nothing
end sub
如果您想测试是否定义了变量(但变量必须是引用类型)
您可以使用反射:
Return AnObject.GetType().GetProperty("TestVar") IsNot Nothing
将其升级为属性并在接口中定义,这难道不是比尝试使用反射更合适吗?然后可以将对象强制转换为接口类型,并以强类型方式处理它
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_不信者的回答(以及随后对GetField的评论)是一个好办法。你的意思是“AnObject.TestVar有值吗”还是“AnObject有一个称为TestVar的变量吗?”我想这不是问题。问题是:对象内部的属性是否存在?VB.Net对待对象的方式与C#的动态对象的方式相同,所以他们实际上是在测试属性的存在性,我认为。如果你在检查“nothing”,你就是在检查它是否分配了值/实例。我们想知道对象是否声明了属性。为此,您需要使用反射。很高兴了解新概念,但此解决方案不适合我的要求。因为我正在将特定对象强制转换为类型对象。比如说,Class1有变量xVar。但是Class2没有。我正在为这两个类创建实例,并将它们转换为一个公共类型对象。现在,我如何才能确定强制对象是否有变量xVar。?每当我在这些强制对象上使用您的修复程序时,它只是不返回任何内容,即使它有该变量。@RajaPrabhuOfficial:似乎您已声明TestVar
仅作为字段,而不是属性。因此,请尝试使用而不是。@RajaPrabhuOfficial-如果您只想检查对象是否有名为TestVar
的内容,甚至可以使用。我假设它是一个属性。我只是更喜欢您所说的GetMember
函数。而且它的工作做得非常好。加一!如果您在回答中添加与GetMember
/GetField
相关的详细信息,那么这将有助于未来的推荐人。对不起,我没有意识到这是一个VB问题,我将把代码更新为VB