【问题标题】:Testing for value equality between two interface instances in c#?在 C# 中测试两个接口实例之间的值相等?
【发布时间】:2016-04-25 05:23:59
【问题描述】:

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

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

然后我尝试在 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);
    }

我遇到的问题是在 setter 中:

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

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

更新

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

【问题讨论】:

    标签: c# interface iequatable


    【解决方案1】:

    你应该明确地调用Equals:

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

    实现IEquatable&lt;T&gt; 不会影响== 运算符。

    【讨论】:

    • 是否可以为接口实现 == 运算符重载?
    • 使用空传播运算符的更短方法:_myIntf?.Equals(value) ?? false
    • @bodangly 不,你不能。看到这个问题:stackoverflow.com/questions/5066281/…
    • @Fabien 对。我还不习惯 C# 6 语法。但是,无论如何,这都是个人喜好的问题。
    【解决方案2】:

    使用Equals 代替==

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

    【讨论】:

    • _myIntfis null 的情况下,您应该使用空传播运算符:_myIntf?.Equals(value) ?? false
    • @Fabien 因此,如果我不想在任何地方允许 null,我实际上可以使用 null 传播运算符将 null 替换为 NullObject 模式吗?
    • @bodangly 我刚刚指出,如果_myIntf 为空,它可能以 NullReferenceException 结束。
    猜你喜欢
    • 1970-01-01
    • 2019-04-03
    • 2015-01-08
    • 1970-01-01
    • 2011-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-03
    相关资源
    最近更新 更多