我在 C# 中探索平等,我正在沿着这条线实现一些东西:
public class MyType
{
public string MyProperty { get; set; }
public MyType(string myProperty)
{
MyProperty = myProperty;
}
protected bool Equals(MyType other)
{
Console.WriteLine("I'm calling the MyType.Equals override");
return MyProperty == other.MyProperty;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((MyType) obj);
}
public override int GetHashCode()
{
throw new NotImplementedException();
}
public static bool operator ==(MyType lhs, MyType rhs)
{
return Equals(lhs, rhs);
}
public static bool operator !=(MyType lhs, MyType rhs)
{
return !(lhs == rhs);
}
}
class Program
{
static void Main(string[] args)
{
var type1 = new MyType("test");
var type2 = new MyType("test");
Console.WriteLine($"type1 == type2 => {type1 == type2}");
Console.Read();
}
}
输出是
我正在调用 MyType.Equals 覆盖
type1 == type2 => True
虽然我完全意识到以这种方式覆盖相等运算符可能会出现的意外,但我想知道的是为什么最终有可能在 MyType 中调用实例虚拟方法(protected bool Equals(MyType other)类)来自静态方法。
好的,鉴于
操作员
关键字,但据我所知,它在 IL 中被翻译为静态方法:
.method public hidebysig specialname static bool op_Equality(class MyType lhs, class MyType rhs) cil managed
我怀疑魔法发生在 object.Equals 静态方法调用的某个地方,但我不知道它实际上是如何工作的。想了解一下吗?