简体   繁体   English

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

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

So I have an interface, lets call it IInterface. 所以我有一个接口,我们称之为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. 然后我尝试在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: 我遇到的问题是在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. Intellisense显示,那里的相等测试只测试引用并将左右两个都视为对象。 I assume this is because there is no operator overload for ==(IInterface left, IInterface right). 我假设这是因为==(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. 我会使用Equals。 Thanks everyone. 感谢大家。

Use Equals instead of == : 使用Equals而不是==

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

You should explicitly call Equals : 你应该明确地调用Equals

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

Implementing IEquatable<T> does not impact the == operator. 实现IEquatable<T>不会影响==运算符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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