El método Equals
es un método virtual que se reemplaza por el tipo Boolean
. Por lo tanto, no importa que esté lanzando el bool
a un object
en la segunda línea; todavía está usando el vtable del tipo para buscar la implementación de Equals
proporcionada por el tipo real del objeto (¡eso es polimorfismo para usted!).
El operador ==
es un operador estático y, por lo tanto, se selecciona la sobrecarga adecuada en tiempo de compilación. El compilador lo ve comparando dos objetos del tipo object
con ese operador y así selecciona la sobrecarga (object, object)
.
Aquí hay un poco estúpido programa para ilustrar la diferencia:
class Thing
{
public virtual void AnnounceSelf()
{
Console.WriteLine("I am a Thing.");
}
public static void AnnounceThing(Thing other)
{
Console.WriteLine("Here is a Thing.");
}
public static void AnnounceThing(OtherThing other)
{
Console.WriteLine("Here is ANOTHER type of Thing.");
}
}
class OtherThing : Thing
{
public override void AnnounceSelf()
{
Console.WriteLine("I am ANOTHER Thing.");
}
}
class Program
{
public static void Main()
{
Thing t = new Thing();
// Outputs "I am a Thing." as expected.
t.AnnounceSelf();
// Outputs "Here is a Thing." as expected.
Thing.AnnounceThing(t);
t = new OtherThing();
// This method is virtual, so even though t is typed as Thing,
// the implementation provided by OtherThing will be called;
// outputs "I am ANOTHER Thing."
t.AnnounceSelf();
// In contrast to above, this method will NOT call the more
// specific overload of AnnounceThing (accepting an OtherThing
// argument) because t is only typed as Thing, so the compiler
// will go with the first;
// outputs "Here is a Thing."
Thing.AnnounceThing(t);
// THIS will output "Here is ANOTHER type of Thing."
Thing.AnnounceThing((OtherThing)t);
}
}