开发者

How to fix warning CA2226 in a C++/CLI application?

I have a C++/CLI class definition where I'm trying to get Equality testing to be Value based rahter than Reference (similar to the behavior of String). The following definitions work:

namespace MyCode
{
 public ref class MyClass
 {
 public:
  MyClass();
  bool operator==(MyClass^ obj) { return Equals(obj); }
  bool operator!=(MyClass^ obj) { return !Equals(obj); }
  virtual bool Equals(MyClass^ obj);
  virtual bool Equals(System::Object^ obj) override;
  virtual int GetHashCode() override;
 };
}

However, my company is now requiring (and rightly so) that all code needs to conform to the Code Analysis rules. Code analysis consistently reports two warnings on the above class:

CA2226 : Microsoft.Usage : Since ''MyClass'' redefines op开发者_Go百科erator '==', it should also redefine operator '!='.
CA2226 : Microsoft.Usage : Since ''MyClass'' redefines operator '!=', it should also redefine operator '=='.

The Microsoft documentation on warning CA2226 makes it clear that this is an important warning and should not be suppressed - but what else can I do?

I'm looking for a way (if possible) to 'fix' the code in order to remove this warning. Is that possible, or do I just need to suppress it?


For a ref class, you're supposed to implement operator==(MyClass^ left, MyClass^ right) as a static member function, this is the one other .NET languages will find.

Your current implementation defines operator==(MyClass%, MyClass^ right) instead, which is unusual.

Note that you can't rely on left != nullptr, you need to test ReferenceEquals(left, nullptr).


This is a .NET implementation detail. Having instance operator overloads is a C++ feature, the code analyzer chokes on it. The .NET way is to have operator overloads as static functions. Notably C# requires this. Solve your problem similar to this:

  static bool operator==(MyClass^ lhs, MyClass^ rhs) { return lhs->Equals(rhs); }
  static bool operator!=(MyClass^ lhs, MyClass^ rhs) { return !lhs->Equals(rhs); }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜