C#相等检查
您为创建的结构和类编写等式检查的方法是什么?
1)“完全”等式检查是否需要大量样板代码(例如重写等于,覆盖GetHashCode,泛型Equals,operator ==,operator!=)? 2)您是否明确指定您的类为IEquatable< T>接口? 3)我是否正确理解,没有实际的方法来自动应用均衡覆盖,当我调用像== b这样的东西,我总是要实现Equals和operator ==成员? 解决方法
你说得对,这是很多锅炉代码,你需要分开实现.
我会建议: >如果要实现价值相等性,则覆盖GetHashCode和Equals(object) – 为==创建重载并实现IEquatable< T>没有这样做可能会导致非常意外的行为 这是一个示例实现: using System; public sealed class Foo : IEquatable<Foo> { private readonly string name; public string Name { get { return name; } } private readonly int value; public int Value { get { return value; } } public Foo(string name,int value) { this.name = name; this.value = value; } public override bool Equals(object other) { return Equals(other as Foo); } public override int GetHashCode() { int hash = 17; hash = hash * 31 + (name == null ? 0 : name.GetHashCode()); hash = hash * 31 + value; return hash; } public bool Equals(Foo other) { if ((object) other == null) { return false; } return name == other.name && value == other.value; } public static bool operator ==(Foo left,Foo right) { return object.Equals(left,right); } public static bool operator !=(Foo left,Foo right) { return !(left == right); } } 是的,这是一个很多样板,很少有实现之间的变化:( ==的实现效率略低于它,因为它将调用等于需要进行动态类型检查的Equals(object),但是替代方案更像是锅炉板,如下所示: public static bool operator ==(Foo left,Foo right) { if ((object) left == (object) right) { return true; } // "right" being null is covered in left.Equals(right) if ((object) left == null) { return false; } return left.Equals(right); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |