Why is this version of Equals called?

Consider the following passage from the Matrix class .

// Both functions below are instance methods of a class Matrix

public bool Equals(Matrix m)
{
    if(m == null || this.RowDim != m.RowDim || this.ColDim != m.ColDim)
        return false;

    for(int i = 0; i < this.RowDim; ++i)
    {
        for(int j = 0; j < this.ColDim; ++j)
        {
            if(System.Math.Abs(this.rows[i][j] - m.rows[i][j]) > 1E-10)
                return false;
        }
    }
    return true;
}

// Overrides System.Object.Equals(object)
public override bool Equals(object obj)
{
    if(!(obj is Matrix))
        throw new InvalidCastException("Cannot cast object instance to instance of type Matrix.");
    return this.Equals((Matrix)obj);
}

Question 1: Given the above, you should not use the function

public bool Equals(Matrix m)

called directly when we compare an object with a type Matrix? Should the "most derived" version of the overloaded function be used? (Here I mean that Matrix is ​​a descendant of Object). This is true:

// m and m2 are instances of class Matrix
m.Equals(m2); // Calls Equals(Matrix)
m.Equals(new object()); // Calls Equals(object)

So, I'm just checking my question with this simple test.

Question 2: However, I have a unit test that looks like

[TestMethod]
public void Test_Matrix_Equals()
{
    RL.Utility.Math.Matrix m = new RL.Utility.Math.Matrix(new double[,] { { 1.2, 3.2 }, { 4.5, 7.8 }, { 5.66, -19.2 } });
    RL.Utility.Math.Matrix m2 = new RL.Utility.Math.Matrix(new double[,] { { 1.2, 3.2 }, { 4.5, 7.8 }, { 5.66, -19.2 } });
    Assert.AreEqual<RL.Utility.Math.Matrix>(m, m2); // Equals(object) is called
}

Why

public override bool Equals(object obj)

but not

public bool Equals(Matrix m)

? I can understand why if I used the non-generic version

Assert.AreEquals

since its parameters are of type Object . But I use the general version, in which I specify the type as a matrix:

Assert.AreEqual<Matrix>

MSDN

, . , .

" "?

operator==

, . , , . , . ?

.

+4

Source: https://habr.com/ru/post/1618461/


All Articles