在 C# 中测试两个接口实例之间的值相等性?

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

所以我有一个接口,我们称它为 IInterface。

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

然后我尝试在实现中实现接口。

    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);
    }

我 运行 遇到的问题是 setter:

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

Intellisense 显示那里的相等性测试仅测试引用并将左右都视为对象。我认为这是因为 ==(IInterface 左,IInterface 右)没有运算符重载。当然,我实际上无法实现该功能,因为 == 需要其中一侧匹配实现 class 的类型。如何正确地确保可以检查两个接口是否相互相等?

更新

知道了,不能为接口实现==。我将使用等于。谢谢大家。

使用Equals代替==:

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

您应该明确调用 Equals:

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

实施 IEquatable<T> 不会影响 == 运算符。