为什么将 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.
为什么要这样做?
我知道 this question 处理重载方法,并使用强制转换来确定哪个要调用的方法的版本.
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
的重载方法而不是该方法的任何其他匹配版本?那么演员们还完成了什么?
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?
推荐答案
如果演员没有执行,那么将选择最具体的版本.
If the cast where not performed, then the most specific version would be chosen.
null
可以是 String
类型或 Object
类型的空引用.因此,如果这两个方法可用,则将调用 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.
如果您有带有 Object
、Integer
和 String
的方法,然后用 null<调用它/code>(并且没有强制转换)会给出编译错误,因为
Integer
和 String
都是有效的并且同样具体(即没有一个是特化的另一个).在这种情况下,您将必须强制转换 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屋!