vendredi 25 mars 2016

Compare Two Structs Using Standard Method (Byte Comparison/Reflection) Even If Equals Method Exists

I have some simple struct, which overrides the Equals() method:

public struct Pair<T> {
    public Pair(T x, T y) {
        X = x; Y = y;
    }

    public T X { get; }
    public T Y { get; }

    public override bool Equals(object obj) {
        var otherPair = (Pair<T>) obj;
        return X.Equals(otherPair.X);
    }
}

According to MSDN, value types without an Equals() method are compared as follows:

If none of the fields of the current instance and obj are reference types, the Equals method performs a byte-by-byte comparison of the two objects in memory. Otherwise, it uses reflection to compare the corresponding fields of obj and this instance.

I wish to compare Pairs using the quoted approach instead of using Pair's own Equals() method, so that the following test passes:

[Test]
public void PairsEqual()
{
    var p1a = new Pair<int>(10, 1);
    var p1b = new Pair<int>(10, 1);
    var p2 = new Pair<int>(10, 2);

    Assert.That(p1a, Is.Not.EqualTo(p2));
    Assert.That(p1a, Is.EqualTo(p1a));
    Assert.That(p1a, Is.EqualTo(p1b));
}

This should ultimately work like a ReferenceEqual for structs. Is this possible? Ideally, I would like to replace the comparison with the original ValueType.Equals() method.





Aucun commentaire:

Enregistrer un commentaire