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

时间:2012-08-31 09:09:49

标签: 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;
        }
    };

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

我做错了什么?

1 个答案:

答案 0 :(得分:10)

您要重载的==运算符无法在C#中访问,而bool equal1 = a == b行会通过引用比较ab

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

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

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