题
实现平等()用于参考类型的困难,它似乎。我当前的规范的执行情况是这样的:
public bool Equals( MyClass obj )
{
// If both refer to the same reference they are equal.
if( ReferenceEquals( obj, this ) )
return true;
// If the other object is null they are not equal because in C# this cannot be null.
if( ReferenceEquals( obj, null ) )
return false;
// Compare data to evaluate equality
return _data.Equals( obj._data );
}
public override bool Equals( object obj )
{
// If both refer to the same reference they are equal.
if( ReferenceEquals( obj, this ) )
return true;
// If the other object is null or is of a different types the objects are not equal.
if( ReferenceEquals( obj, null ) || obj.GetType() != GetType() )
return false;
// Use type-safe equality comparison
return Equals( (MyClass)obj );
}
public override int GetHashCode()
{
// Use data's hash code as our hashcode
return _data.GetHashCode();
}
我认为,这种涵盖了所有角(继承及诸)的情况下,但我可能是错误的。你们怎么想的?
解决方案
我写了一个相当全面的指导,这一同时回来。一开始你就等于实现应该是共用(即载采取的一个对象应该通过一个把强类型的对象)。另外需要考虑的事情,例如你的对象应该是不可改变的,因为需要替代GetHashCode.这里更多的信息:
http://gregbeech.com/blog/implementing-object-equality-in-dotnet
其他提示
更好的希望,这一点。_data不是null如果这也是一个参照类型。
public bool Equals( MyClass obj )
{
if (obj == null) {
return false;
}
else {
return (this._data != null && this._data.Equals( obj._data ))
|| obj._data == null;
}
}
public override bool Equals( object obj )
{
if (obj == null || !(obj is MyClass)) {
return false;
}
else {
return this.Equals( (MyClass)obj );
}
}
public override int GetHashCode() {
return this._data == null ? 0 : this._data.GetHashCode();
}
关于继承,我认为你应该只是让OO模式不会魔法。
具体地说, GetType()
检查应该被删除,它可能会破坏多态性。
我同意chakrit、对象的不同类型应当允许在语义上的平等如果他们有相同数据或身份证。
就个人而言,我用如下:
public override bool Equals(object obj)
{
var other = obj as MyClass;
if (other == null) return false;
return this.data.Equals(other.data);
}
这取决于你是否正在写一个值的类型或参考类型。对于一个排序的价值类,我建议:一个代码段Visual Studio2005年,实现了一个骨架的价值型秉承框架的设计准则
不隶属于 StackOverflow