2009-11-30 11 views
40

Utilizzando reflection per ottenere un MethodInfo, voglio verificare se il tipo restituito è typeof System.Void.Come testare se MethodInfo.ReturnType è un tipo di System.Void?

Testing se è System.Int32 funziona bene

myMethodInfo.ReturnType == typeof(System.Int32) 

ma

myMethodInfo.ReturnType == typeof(System.Void) 

non viene compilato? Attualmente sto testando se la rappresentazione della stringa del nome è "System.Void", che sembra molto sbagliato.

+1

che errore state ottenendo quando si costruisce quel codice ? –

+0

Se un metodo restituisce Void, significa che non restituisce nulla, quindi perché non invertire la logica e verificare ciò che potrebbe essere restituito? Solo un'idea ... –

+2

Il compilatore dice "System.Void non può essere usato da C# - usa typeof (void) per ottenere il tipo void". Ah, leggi l'errore. DOH! –

risposta

53

Non è possibile utilizzare System.Void direttamente, ma può accedervi utilizzando typeof(void).

Diverse persone sottolineano (here e nei commenti here per esempio) che la ragione di questo è che il ECMA Standard 335, Partizione II, sezione 9.4 dice:

The following kinds of type cannot be used as arguments in instantiations (of generic types or methods):

  • Byref types (e.g., System.Generic.Collection.List 1<string&> is invalid)
  • Value types that contain fields that can point into the CIL evaluation stack (e.g., List<System.RuntimeArgumentHandle>)
  • void (e.g., List<System.Void> is invalid)
+14

Sono un tale idiota. Il messaggio di errore dice "use typeof (void)". –

+2

Basta nascondere la finestra di errore! ;) Ma è terribilmente strano. –

18

Quando costruisco questo, ottengo l'errore:

System.Void cannot be used from C# -- use typeof(void) to get the void type object

Suona come questa è la risposta ...

+0

Sì, fallisco. Avrei accettato anche la risposta RTFM :) –

Problemi correlati