在。net引用源中转换为对象

时间:2022-03-07 14:32:20

I was going through the OperatingSystem.cs file in the .NET reference source and noted this code in line 50:

我正在通过操作系统。cs文件在。net参考源代码中,并注意到第50行中的代码:

if ((Object) version == null)

version is an object of class Version, which means version derives from Object. If that is so, isn't it redundant casting to Object? Wouldn't it be the same as this?

version是类version的对象,即version是从object派生的。如果是这样,对对象进行强制转换不是多余的吗?不是和这个一样吗?

if (version == null)

1 个解决方案

#1


91  

No, it's not equivalent - because Version overloads the == operator.

不,它不是等价的——因为Version会重载=运算符。

The snippet which casts the left operand to Object is equivalent to:

将左操作数转换为对象的代码片段相当于:

if (Object.ReferenceEquals(version, null))

... rather than calling the operator== implementation in Version. That's likely to make a nullity check as its first action anyway, but this just bypasses the extra level.

…而不是在版本中调用操作符== =实现。无论如何,这很可能作为它的第一个操作执行一个nullity检查,但是这只是绕过了额外的级别。

In other cases, this can make a very significant difference. For example:

在其他情况下,这可以产生非常重要的影响。例如:

string original = "foo";
string other = new string(original.ToCharArray());
Console.WriteLine(original == other); // True
Console.WriteLine((object) original == other); // False

#1


91  

No, it's not equivalent - because Version overloads the == operator.

不,它不是等价的——因为Version会重载=运算符。

The snippet which casts the left operand to Object is equivalent to:

将左操作数转换为对象的代码片段相当于:

if (Object.ReferenceEquals(version, null))

... rather than calling the operator== implementation in Version. That's likely to make a nullity check as its first action anyway, but this just bypasses the extra level.

…而不是在版本中调用操作符== =实现。无论如何,这很可能作为它的第一个操作执行一个nullity检查,但是这只是绕过了额外的级别。

In other cases, this can make a very significant difference. For example:

在其他情况下,这可以产生非常重要的影响。例如:

string original = "foo";
string other = new string(original.ToCharArray());
Console.WriteLine(original == other); // True
Console.WriteLine((object) original == other); // False