【发布时间】:2013-04-25 20:01:16
【问题描述】:
只是好奇。
在对象上调用.GetType() 是否会返回null?
假设用法:
public Type MyMethod( object myObject )
{
return myObject.GetType();
}
【问题讨论】:
只是好奇。
在对象上调用.GetType() 是否会返回null?
假设用法:
public Type MyMethod( object myObject )
{
return myObject.GetType();
}
【问题讨论】:
对象上的GetType 永远不会返回null - 至少它将是对象类型。如果 myObject 为 null,那么当您尝试调用 GetType() 时会出现异常
【讨论】:
dynamic关键字和元编程后,这个答案不再正确!看到这个:stackoverflow.com/a/42968060/375958
不,它不会返回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>。
(将原始概念归功于 Marc Gravell。)
【讨论】:
如果 myObject 参数为 null,那么您将无法对其调用 GetType()。将抛出 NullReferenceException。否则,我想你会没事的。
【讨论】:
http://msdn.microsoft.com/en-us/library/system.object.gettype(VS.85).aspx
MSDN 只列出一个类型对象作为返回值。
我想除此之外,您所能得到的只是“未设置为对象的实例”异常(或者可能是它的空引用),因为 MSDN 确实说 INSTANCE。
【讨论】:
基本上,不,它不能(永远返回 null)也不会。
【讨论】: