2010-02-04 91 views

回答

14

对象上的GetType永远不会返回null - 至少它将是类型对象。如果myObject为null,那么当您尝试调用GetType()时,您会遇到异常

2

如果myObject的参数为空,那么你将无法调用的GetType()就可以了。 NullReferenceException将被抛出。否则,我认为你会好的。

0

基本上,不,它不能(永远不会返回null),也不会。

5

不,它不会返回null。但这是一个需要注意的问题!

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()); 
} 

这里有一定T输出:

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

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

什么是T?答:任何Nullable<U>

(信用原单概念马克Gravell)

+0

我看你做了什么,有;-p – 2010-02-04 16:29:12

+0

@Marc Gravell:我做你的信用,如果这是你的意思。我无法找到您首次提交的帖子,但提供链接?我认为这是在C#/ .net gotcha线程中。 – jason 2010-02-04 16:37:11