2014-01-07 115 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); 

这简化了很多。