简体   繁体   中英

Testing for value equality between two interface instances in c#?

So I have an interface, lets call it IInterface.

public interface IInterface : IEquatable<IInterface>
{
    string Name { get; set; }
    int Number { get; }
    Task<bool> Update();
}

Then I try and implement the interface in Implementation.

    public bool Equals(IInterface other)
    {
        if (other == null) return false;

        return (this.Name.Equals(other.Name) && this.Number.Equals(other.Number));
    }

    public override int GetHashCode()
    {
        return this.Number.GetHashCode();
    }

    public override bool Equals(object obj)
    {
        var other = obj as IInterface ;
        return other != null && Equals(other);
    }

    public static bool operator ==(Implementation left, IInterface right)
    {
        if (ReferenceEquals(left, right)) return true;

        if (ReferenceEquals(left, null)) return false;

        return left.Equals(right);
    }

    public static bool operator !=(Implementation left, IInterface right)
    {
        return !(left == right);
    }

The problem I am running into is in a setter:

    public IInterface MyIntf
    {
        get { return _myIntf; }
        set
        {
            if (_myIntf == value) { return; }
            _myIntf = value;
        }

Intellisense is showing that the equality test there is testing the references only and treating both left and right as objects. I assume this is because there is no operator overload for ==(IInterface left, IInterface right). Of course, I cannot actually implement that function because == requires one of the sides to match the type of the implementing class. How does one properly make sure two interfaces can be checked for equality against each other?

Update

Got it, you cannot implement == for an interface. I will use Equals. Thanks everyone.

Use Equals instead of == :

public IInterface MyIntf
{
    get { return _myIntf; }
    set
    {
        if (_myIntf.Equals(value)) { return; }
        _myIntf = value;
    }
}

You should explicitly call Equals :

if (_myIntf != null && _myIntf.Equals(value)) { return; }

Implementing IEquatable<T> does not impact the == operator.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM