Object.GetType()是否可以返回null?
只是好奇。
是否有任何时候调用。对象上的.GetType()
将返回null?
假设用法:
public Type MyMethod( object myObject ) { return myObject.GetType(); }
对象上的GetType永远不会返回null – 至少它将是object类型。 如果myObject为null,那么当你尝试调用GetType()时,你会得到一个exception
不,它不会返回null
。 但这是一个需要注意的问题!
static void WhatAmI() 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
。
(Marc Gravell的信用原创概念。)
如果myObject参数为null,则您将无法在其上调用GetType()。 将抛出NullReferenceException。 否则,我认为你会没事的。
http://msdn.microsoft.com/en-us/library/system.object.gettype(VS.85).aspx
MSDN仅列出类型对象作为返回值。
我想你可以得到的只是“未设置为对象的实例”exception(或者可能是它的空引用)因为MSDN确实说过INSTANCE。
基本上,不,它不能(永远不会返回null),也不会。