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

标签 c# interface iequatable

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

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

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

    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 右)没有运算符重载。当然,我实际上无法实现该功能,因为 == 需要其中一侧匹配实现类的类型。如何正确地确保可以检查两个接口(interface)是否相互相等?

更新

明白了,你不能为一个接口(interface)实现==。我将使用等于。谢谢大家。

最佳答案

您应该显式调用 Equals :

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

实现 IEquatable<T>不影响 ==运营商。

关于c# - 在 C# 中测试两个接口(interface)实例之间的值相等性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36828803/

相关文章:

c# - 尝试从 notepad++ .NET 插件创建新选项卡

c# - 在图片盒中绘制颜色?

c# - c# 中的 obj1.Equals(obj2) 和 static Object.Equals(obj1, obj2) 有什么区别?

c# - Distinct 不使用 LINQ to Objects

c# - GetHashCode() 返回值应该基于原始对象的状态还是修改后的对象的状态?

C# 随机数

c# - 没有 xsi :type 的派生对象的序列化

.net - 添加插件支持 : Interface or Base class to inherit?

c++ - C++ 中的工厂模式——这样做正确吗?

c++ - 尝试编译 .dll 时,出现 interface 关键字错误