我有一些这样的代码:
我应该如何实现运算符 == 以便在变量是接口 IMyClass 时调用它?
public class MyClass : IMyClass
{
public static bool operator ==(MyClass a, MyClass b)
{
if (ReferenceEquals(a, b))
return true;
if ((Object)a == null || (Object)b == null)
return false;
return false;
}
public static bool operator !=(MyClass a, MyClass b)
{
return !(a == b);
}
}
class Program
{
static void Main(string[] args)
{
IMyClass m1 = new MyClass();
IMyClass m2 = new MyClass();
MyClass m3 = new MyClass();
MyClass m4 = new MyClass();
Console.WriteLine(m1 == m2); // does not go into custom == function. why not?
Console.WriteLine(m3 == m4); // DOES go into custom == function
}
}