4

我有以下 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;
        }
    };

当我尝试从 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);

我做错了什么?

4

1 回答 1

11

==您重载的运算符在 C# 中不可访问,并且行bool equal1 = a == b比较ab通过引用。

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

static bool operator==(MyClass^ a, MyClass^ b)
{
  return a->val == b->val;
}

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

于 2012-08-31T09:22:24.463 回答