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

わずか 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 に答える