2009-06-16 11 views

risposta

14

Siete alla ricerca di qualcosa di simile TypeOf? Funziona solo con tipi di riferimento, non int/etc.

If TypeOf "value" Is String Then 
    Console.WriteLine("'tis a string, m'lord!") 

Oppure si desidera confrontare due diverse istanze di variabili? Funziona anche per i tipi ref:

Dim one As Object = "not an object" 
Dim two As Object = "also not an object, exactly" 
Dim three as Object = 3D 

If one.GetType.Equals(two.GetType) Then WL("They are the same, man") 
If one.GetType Is two.GetType then WL("Also the same") 
If one.GetType IsNot three.GetType Then WL("but these aren't") 

Si potrebbe anche usare gettype() like quindi, se non si sta utilizzando due oggetti:

If three.GetType Is gettype(integer) then WL("is int") 

Se volete vedere se qualcosa è una sottoclasse di un altro tipo (e sono in .net 3.5):

If three.GetType.IsSubclassOf(gettype(Object)) then WL("it is") 

Ma se si vuole fare che nelle versioni precedenti, è necessario capovolgere esso (strano a guardare) e l'uso:

If gettype(Object).IsAssignableFrom(three.GetType) Then WL("it is") 

Tutti questi compila in SnippetCompiler, quindi vai DL se non ce l'hai.

3
TypeOf obj Is MyClass 
0

VB equivalente alla tua domanda legata è quasi identico:

Dim result As Boolean = obj.GetType().IsAssignableFrom(otherObj.GetType())