2012-01-20 24 views
7

che sto cercando di scrivere l'equivalente di VBScript di una funzione simile a ciò che è in basso:Restituisce Null o Nothing dalla funzione VBScript?

object getObject(str) 
{ 
    if (...) 
    { 
     return object_goes_here; 
    } 

    return null; 
} 

La mia ipotesi è al di sotto, solo che non sto capire la differenza tra il nulla e Null. Come chiamante, preferirei verificare se il valore di ritorno è impostato utilizzando IsNull() rispetto a X Is Nothing.

Function getObject(str) 
    If ... Then 
     Set getObject = object_goes_here 
     Exit Function 
    End If 

    Set getObject = Nothing // <-- or should this be Null? 
End Function 

risposta

14

Il modo corretto per non restituire un oggetto è quello di restituire Nothing e test Is Nothing.

VB Null è un valore speciale di tipo Variante/Nullo. Esistono altri valori speciali, come Variant/Empty o Variant/Error. Hanno tutti il ​​loro uso, ma non è quello giusto.

+0

In che modo InStr riesce a farla franca? Sembra che restituisca l'equivalente .NET di Nullable . http://www.w3schools.com/vbscript/func_instr.asp – jglouie

+1

@jglouie 'InStr' accetta un' VARIANT' come parametro, non un oggetto. Quindi esamina il 'VARIANT' e prova a darti quello che ti aspettavi. Restituire un 'Null' se un operando stringa è' Null' è un concetto comune molto standard proveniente da database. Per quanto riguarda le stringhe in VB6 (e VBScript), non sono comunque oggetti, non possono essere 'Nothing'. Beh, sono in grado di farlo, ma si chiama 'vbNullString' e non viene rilevato con' Is Nothing'. – GSerg

4

Utilizzare il secondo scheletro Funzione. Evita il valore Null quando si ha a che fare con oggetti, a causa dell'abominio di Set Assignment.

Dim oX : Set oX = getObject(...) 
If oX Is Nothing Then 
    ... 
Else 
    nice object to work with here 
End If 

vs

Dim vX : vX = getObject(...) ' <-- no Set, no object 
If IsNull(vX) Then 
    ... 
Else 
    no object to work with here 
End If 
2

Nel codice di esempio, l'oggetto diventa sempre Nothing perché questa è l'ultima azione. Questo è come dovrebbe essere:

Function getObject(str) 
    If ... Then 
     Set getObject = object_goes_here 
     Exit Function 
    End If 
    Set getObject = Nothing 
End Function 

o:

Function getObject(str) 
    Set getObject = Nothing 
    If ... Then 
     Set getObject = object_goes_here 
    End If 
End Function 

La risposta di GSerg è corretta: si dovrebbe usare Niente. Inoltre, per verificare se un oggetto ha un riferimento null, utilizzare:

If Not object Is Nothing Then 
    ' do something 
End If 
+0

Oops, ho omesso la linea di uscita, grazie. Questa non era la mia domanda, ma chiarirà chiunque altro cerchi questa domanda. – user1128144

Problemi correlati