2012-08-31 158 views
4

我有下面的C++/CLI類:C++/CLI重載運營商不通過C#訪問

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

[如何在C++/CLI應用程序中修復警告CA2226?](http://stackoverflow.com/questions/4589426/how-to-fix-warning-ca2226-in-ac-cli-application ) –

回答

10

您正在超載的==運算符在C#中不可訪問,行bool equal1 = a == b比較ab作爲參考。

二元運算符在C#靜態方法重寫,你需要提供這個操盤手:

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

當重寫==你也應該重寫!=。在C#中,這實際上是由編譯器強制執行的。