我有以下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);
我做错了什么?
答案 0 :(得分:10)
您要重载的==
运算符无法在C#中访问,而bool equal1 = a == b
行会通过引用比较a
和b
。
二进制运算符被C#中的静态方法覆盖,您需要提供此运算符:
static bool operator==(MyClass^ a, MyClass^ b)
{
return a->val == b->val;
}
覆盖==
时,您还应覆盖!=
。在C#中,这实际上是由编译器强制执行的。