bod*_*gly 5 c# interface iequatable
所以我有一个接口,我们称之为 IInterface。
public interface IInterface : IEquatable<IInterface>
{
string Name { get; set; }
int Number { get; }
Task<bool> Update();
}
Run Code Online (Sandbox Code Playgroud)
然后我尝试在实现中实现接口。
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);
}
Run Code Online (Sandbox Code Playgroud)
我遇到的问题是在 setter 中:
public IInterface MyIntf
{
get { return _myIntf; }
set
{
if (_myIntf == value) { return; }
_myIntf = value;
}
Run Code Online (Sandbox Code Playgroud)
Intellisense 显示那里的相等性测试仅测试引用并将左右都视为对象。我认为这是因为 ==(IInterface left, IInterface right) 没有运算符重载。当然,我实际上无法实现该函数,因为 == 需要其中一侧来匹配实现类的类型。如何正确确保可以检查两个接口是否相互相等?
更新
明白了,你不能为接口实现 == 。我将使用等于。谢谢大家。
您应该明确调用Equals:
if (_myIntf != null && _myIntf.Equals(value)) { return; }
Run Code Online (Sandbox Code Playgroud)
实施IEquatable<T>不会影响==操作员。