Pregunta

A c++/cli ref class DataEntity implements Equals and HashCode. I can check the behavior of the Equals implementation via:

entity1.Equals(entity2);

(C# source) and it works correctly. If I now have a list of such DataEntities and I call list1.Equlas(list2), the DataEntity#Equals method never gets called.

What is the reason for, and how can I use the List.Equals(...) method correcty?


C++/CLI source:

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# Unit test case which fails!

[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));
}
¿Fue útil?

Solución

List<T> doesn't override Object.Equals. Therefore, you get the default implementation of Equals, which is reference equality.

In order to test if the list contents are equal, you need to iterate the lists and compare each element, or use the Linq method mentioned in the linked duplicate question.

Otros consejos

In case of unit testing there is a utility method called:

CollectionAssert.AreEqual(expectedList, actualList);

which simplifies it a lot.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top