2014-01-07 113 views
0

C++/cli ref class DataEntity實現Equals和HashCode。我可以通過檢查Equals實施的行爲:如何檢查C++/cli ref項目列表是否相等?

entity1.Equals(entity2); 

(C#源)和它工作正常。 如果我現在有一個這樣的DataEntities的列表,我打電話list1.Equlas(list2)DataEntity#Equals方法永遠不會被調用。

是什麼原因導致的,我該如何使用List.Equals(...)方法糾正?


C++/CLI源:

public ref class DataEntity : System::Object 
{ 
public: 
    DataEntity(System::String^ name, 
     System::String^ val) 
     : m_csName(name), 
     m_csValue(val) {} 

    System::String^ GetName() { return m_csName; } 
    System::String^ GetValue() { return m_csValue; } 
    virtual bool Equals(Object^ obj) override { 
     if(!obj){ 
      return false; 
     } 
     DataEntity^ other = (DataEntity^)obj; 
     if(other){ 
      if(m_csName->Equals(other->m_csName) && 
       m_csValue->Equals(other->m_csValue)){ 
        return true; 
      } 
      return false; 
     } 
     return false; 
    } 
    virtual int GetHashCode() override { 
     const int iPrime = 17; 
     long iResult = 1; 
     iResult = iPrime * iResult + m_csName->GetHashCode(); 
     iResult = iPrime * iResult + m_csValue->GetHashCode(); 
     return iPrime; 
    } 

private: 
    System::String^ m_csName;  
    System::String^ m_csValue; 
}; 

C#單位測試用例從而未能!

[Test] 
public void Test() 
{ 
    DataEntity de1 = new DataEntity("A", "B"); 
    List<DataEntity> des1 = new List<DataEntity>(); 
    des1.Add(de1); 
    List<DataEntity> des2 = new List<DataEntity>(); 
    des2.Add(de1); 

    Assert.IsTrue(des1.Equals(des2)); 
} 

回答

0

List<T>不會覆蓋Object.Equals。因此,您將獲得Equals的默認實現,即參考平等。

爲了測試列表內容是否相等,您需要迭代列表並比較每個元素,或者使用鏈接重複問題中提到的Linq方法。

0

在單元測試的情況下,有一個稱爲公用方法:

CollectionAssert.AreEqual(expectedList, actualList); 

這簡化了很多。