简体   繁体   English

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

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

Merely curious. 只是好奇。

Is there any time when calling .GetType() on an object will return null? 是否有任何时候调用。对象上的.GetType()将返回null?

Hypothetical usage: 假设用法:

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

GetType on an object can never return null - at the very least it will be of type object. 对象上的GetType永远不会返回null - 至少它将是object类型。 if myObject is null, then you'll get an exception when you try to call GetType() anyway 如果myObject为null,那么当你尝试调用GetType()时,你会得到一个异常

No, it will not return null . 不,它不会返回null But here is a gotcha to be aware of! 但这是一个需要注意的问题!

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

Here's the output for a certain T : 这是某个T的输出:

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

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

What is T ? 什么是T Answer: any Nullable<U> . 答案:任何Nullable<U>

(Credit orginal concept to Marc Gravell.) (Marc Gravell的信用原创概念。)

If the myObject parameter is null, then you won't be able to call GetType() on it. 如果myObject参数为null,则您将无法在其上调用GetType()。 A NullReferenceException will be thrown. 将抛出NullReferenceException。 Otherwise, I think you will fine. 否则,我认为你会好的。

http://msdn.microsoft.com/en-us/library/system.object.gettype(VS.85).aspx http://msdn.microsoft.com/en-us/library/system.object.gettype(VS.85).aspx

MSDN only lists a type object as the return value. MSDN仅列出类型对象作为返回值。

I'd imagine other than that all you can get is a "not set to an instance of an object" exception (or maybe its null reference) Because MSDN does say INSTANCE. 我想你可以得到的只是“没有设置为对象的实例”异常(或者它的空引用)因为MSDN确实说过INSTANCE。

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

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

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