2010-02-04 13 views
7

Semplicemente curioso.Può Object.GetType() restituire mai null?

C'è qualche momento in cui chiamare .GetType() su un oggetto restituirà nulla?

utilizzo ipotetico:

public Type MyMethod(object myObject) 
{ 
    return myObject.GetType(); 
} 

risposta

14

GetType su un oggetto non può mai restituire null - per lo meno sarà di tipo oggetto. se myObject è nullo, si otterrà un'eccezione quando si tenta di chiamare GetType() in ogni caso

2

Se il parametro myObject è nullo, allora non sarà in grado di chiamare GetType() su di esso. Sarà lanciata una NullReferenceException. Altrimenti, penso che starai bene.

0

Fondamentalmente, no, non può (mai restituire null) e non lo farà.

5

No, non restituirà null. Ma ecco una cosa da prendere in considerazione!

static void WhatAmI<T>() where T : new() { 
    T t = new T(); 
    Console.WriteLine("t.ToString(): {0}", t.ToString()); 
    Console.WriteLine("t.GetHashCode(): {0}", t.GetHashCode()); 
    Console.WriteLine("t.Equals(t): {0}", t.Equals(t)); 

    Console.WriteLine("t.GetType(): {0}", t.GetType()); 
} 

ecco l'output per un certo T:

t.ToString(): 
t.GetHashCode(): 0 
t.Equals(t): True 

Unhandled Exception: System.NullReferenceException: Object reference not set to 
an instance of an object. 

Che cosa è T? Risposta: qualsiasi Nullable<U>.

(. Credit concept originale di Marc Gravell)

+0

vedo quello che hai fatto lì ;-p –

+0

@ Marc Gravell: ho fatto di credito se è questo che vuoi dire. Non sono riuscito a trovare il post in cui l'hai presentato per primo per fornire un link? Ho pensato che fosse nel thread getcha C# /. NET. – jason

Problemi correlati