不通过C#访问C++/CLI重载操作符

Mau*_*wer 4 c# c++-cli operator-overloading

我有以下C++/CLI类:

 public ref class MyClass
    {
    public:
        int val;
        bool operator==(MyClass^ other)
        {
            return this->val == other->val;
        }

        bool Equals(MyClass^ other)
        {
            return this == other;
        }
    };
Run Code Online (Sandbox Code Playgroud)

当我尝试从C#验证两个实例MyClass是否相等时,我得到了错误的结果:

MyClass a = new MyClass();
MyClass b = new MyClass();

//equal1 is false since the operator is not called
bool equal1 = a == b;
//equal2 is true since the comparison operator is called from within C++\CLI
bool equal2 = a.Equals(b);
Run Code Online (Sandbox Code Playgroud)

我做错了什么?

Mar*_*age 10

==您正在重载的运算符无法在C#中访问,并且行bool equal1 = a == b比较ab引用.

二进制运算符被C#中的静态方法覆盖,您需要提供此运算符:

static bool operator==(MyClass^ a, MyClass^ b)
{
  return a->val == b->val;
}
Run Code Online (Sandbox Code Playgroud)

覆盖时,==你也应该覆盖!=.在C#中,这实际上是由编译器强制执行的.