简体   繁体   English

用于Object.Equals的IL代码生成

[英]IL code generation for Object.Equals

Even though the type resolved to Int32 at runtime, the IL shows it called object.equals instead of int32.Equals, like this example: 即使类型在运行时解析为Int32,IL也会将其显示为object.equals而不是int32.Equals,例如以下示例:

object x = 5;
object y = 5;
Console.WriteLine(x.Equals(y));

But it returns True, that means it performed a value equality. 但是它返回True,这意味着它执行了一个值相等。 I guess my question is shouldn't IL should have been instance bool [mscorlib]System.Int32::Equals(int32) 我想我的问题是IL应该不应该是instance bool [mscorlib]System.Int32::Equals(int32)

// [18 13 - 18 27]
IL_0001: ldc.i4.5     
IL_0002: box          [mscorlib]System.Int32
IL_0007: stloc.0      // x

// [19 13 - 19 27]
IL_0008: ldc.i4.5     
IL_0009: box          [mscorlib]System.Int32
IL_000e: stloc.1      // y
// [21 13 - 21 46]
IL_000f: ldloc.0      // x
IL_0010: ldloc.1      // y
IL_0011: callvirt     instance bool [mscorlib]System.Object::Equals(object)
IL_0016: call         void [mscorlib]System.Console::WriteLine(bool)
IL_001b: nop          

The object.Equals method is virtual, and is overridden in Int32 . object.Equals方法是虚拟的,并且在Int32被覆盖。 callvirt is a polymorphic call - it will check the run-time type of the object before calling a virtual method, and use the correct implementation. callvirt是一个多态调用-它将在调用虚拟方法之前检查对象的运行时类型,并使用正确的实现。

Int32 implements IEquatable<T> interface and defines another overload of Equals Int32实现IEquatable<T>接口并定义另一个Equals重载

public bool Equals(Int32 obj);

The compiler can choose this overload only if the compile-time types of both the parameter and the value it's called on is Int32 . 仅当参数及其调用的值的编译时类型均为Int32 ,编译器才能选择此重载。 Here, the compile-time types are object , so the compiler can only use the object.Equals(object obj) overload. 在这里,编译时类型是object ,所以编译器只能使用object.Equals(object obj)重载。

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

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