繁体   English   中英

Object.GetType()是否可以返回null?

[英]Can Object.GetType() ever return null?

只是好奇。

是否有任何时候调用。对象上的.GetType()将返回null?

假设用法:

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

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

不,它不会返回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),也不会。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM