为什么将null转换为Object? [英] Why cast null to Object?
问题描述
我在我正在处理的一些代码中找到了一个位置 null
被转换为 Object
,因为它是传递给方法。
I found a spot in some code I'm working on where null
is cast to Object
as it is passed to a method.
为什么要这样做?
我知道这个问题处理重载方法,并使用强制转换来确定要调用哪个版本的方法。
I am aware of this question which deals with overloaded methods, and using the cast to determine which version of the method to call.
但是如果没有执行强制转换,那么选择类型为 Object
的参数的重载方法不会超过任何其他匹配版本如果使用null参数调用该方法的方法?那么演员还能做些什么?
But if the cast were not performed, wouldn't an overloaded method with a parameter typed as Object
be chosen over any other matching version of the method if the method is called with a null argument? So what else does the cast accomplish?
推荐答案
如果演员不,那么<将选择strong>最具体的版本。
null
可以是类型的空引用 String
或类型对象
。因此,如果这两种方法可用,则将调用 String
方法。
null
could be a null-reference of type String
or of type Object
. So if those two methods are available, then the String
method will be called.
如果你有方法对象
,整数
和 字符串
然后用 null
调用它(并且没有强制转换)会产生编译错误,因为 Integer
和字符串
既有效又同样具体(即没有一个是另一个的专业化)。在这种情况下,您拥有来投射 null
来指定要调用的方法。
If you have methods with Object
, Integer
and String
then calling that with null
(and no cast) would give a compilation error because Integer
and String
are both valid and equally specific (i.e. none is a specialization of the other). In that case you would have to cast null
to specify which method to call.
这篇关于为什么将null转换为Object?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!