[英]Please explain the technique used in this code to test Object Equality and Identity
Please explain the technique used in this code to test Object Equality and Identity. 请解释此代码中用于测试对象平等和身份的技术。
Better, if you can supply me any web-link/book-reference for detailed discussion. 更好,如果您能为我提供任何网站链接/书籍参考,以供详细讨论。
[Serializable]
public abstract class BusinessObject<T> : IBusinessObject where T : BusinessObject<T>
{
private int? requestedHashCode;
public virtual int ID { get; set; }
public virtual bool Equals(IBusinessObject other)
{
if (null == other || !GetType().IsInstanceOfType(other))
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
bool otherIsTransient = Equals(other.ID, default(T));
bool thisIsTransient = IsTransient();
if (otherIsTransient && thisIsTransient)
{
return ReferenceEquals(other, this);
}
return other.ID.Equals(ID);
}
protected bool IsTransient()
{
return Equals(ID, default(T));
}
public override bool Equals(object obj)
{
var that = obj as IBusinessObject;
return Equals(that);
}
public override int GetHashCode()
{
if (!requestedHashCode.HasValue)
{
requestedHashCode = IsTransient() ? base.GetHashCode() : ID.GetHashCode();
}
return requestedHashCode.Value;
}
}
What is a transient object? 什么是瞬态物体?
other
is an instance of the same type as the current object. other
是否是与当前对象相同类型的实例。 If not, they're not equal other
and the current object are the same instance. other
对象和当前对象是否是同一个实例。 If they are, obviously they are equal other
and the current object are transient (ie not yet persisted), they don't have an ID, so they can't be compared by ID. other
对象和当前对象都是暂时的(即尚未持久化),则它们没有ID,因此无法通过ID进行比较。 Instead, they are compared by reference. I think what the code is trying to do is say "has it got an ID yet", ie a "transient" object might (if I read the code's intent correctly) be one that is not yet saved to the DB. 我认为代码试图做的是“它还有ID吗”,即“瞬态”对象可能(如果我正确读取代码的意图)是尚未保存到DB的那个。 Then equality is defined as:
然后将相等定义为:
unfortunately the implementation looks completely broken, as Equals(ID, default(T))
is meaningless when T
is something completely different (a BusinessObject<T>
) - hence default(T)
will always be null
and ID
will never be null
(it is not nullable). 不幸的是,实现看起来完全破坏了,因为当
T
是完全不同的东西( BusinessObject<T>
)时, Equals(ID, default(T))
毫无意义 - 因此default(T)
将始终为null
, ID
将永远不为null
(它是不可空的)。 So nothing will ever report as transient. 所以没有任何东西可以报告为瞬态。
Additionally, this code: 另外,这段代码:
if (null == other || !GetType().IsInstanceOfType(other))
is hugely inefficient. 非常低效。 I suspect something involving
as
would be far preferable, but again: the code looks so... tortured... that I'm loathe to second-guess the intent. 我怀疑涉及一些
as
将远远最好,但再次:代码看起来如此... ...折磨,我很厌恶第二猜测意图。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.