为什么 == 实现不为 Guid 调用 Equals?
Why doesn't == implementation call Equals for Guid?
我在 .NET Framework 中 GUID 类型的源代码中看到 Equals 和 ==
运算符的实现执行非常相似的代码。
为什么 ==
运算符不对第一个参数调用 Equals 方法?像这样:
public static bool operator ==(Guid a, Guid b)
{
return a.Equals(b);
}
评论很有说服力:
public static bool operator ==(Guid a, Guid b)
{
// Now compare each of the elements
这本身没有意义。在文件的其他地方寻找该评论:
public bool Equals(Guid g)
{
// Now compare each of the elements
还有
// Returns true if and only if the guid represented
// by o is the same as this instance.
public override bool Equals(Object o)
{
Guid g;
// Check that o is a Guid first
if(o == null || !(o is Guid))
return false;
else g = (Guid) o;
// Now compare each of the elements
注释仅在最后一种方法中有意义。这非常有力地表明 Guid.Equals(Object)
实施是第一位的。
如果 Guid.operator ==
和 Guid.Equals(Guid)
在 Guid.Equals(Object)
之上实现,那将是糟糕的,或者至少不是最佳的,因为最后一个方法 需要 无意义的分配,虽然在常见情况下几乎不会引起注意,但肯定会在某些代码中发生 Guid
比较,在紧密循环中分配是可测量的。
现在,当然可以使 operator ==
使用 Equals(Guid)
,反之亦然,但将其复制和粘贴两次而不是一次确实没有任何额外的工作。
我在 .NET Framework 中 GUID 类型的源代码中看到 Equals 和 ==
运算符的实现执行非常相似的代码。
为什么 ==
运算符不对第一个参数调用 Equals 方法?像这样:
public static bool operator ==(Guid a, Guid b)
{
return a.Equals(b);
}
评论很有说服力:
public static bool operator ==(Guid a, Guid b) { // Now compare each of the elements
这本身没有意义。在文件的其他地方寻找该评论:
public bool Equals(Guid g) { // Now compare each of the elements
还有
// Returns true if and only if the guid represented // by o is the same as this instance. public override bool Equals(Object o) { Guid g; // Check that o is a Guid first if(o == null || !(o is Guid)) return false; else g = (Guid) o; // Now compare each of the elements
注释仅在最后一种方法中有意义。这非常有力地表明 Guid.Equals(Object)
实施是第一位的。
如果 Guid.operator ==
和 Guid.Equals(Guid)
在 Guid.Equals(Object)
之上实现,那将是糟糕的,或者至少不是最佳的,因为最后一个方法 需要 无意义的分配,虽然在常见情况下几乎不会引起注意,但肯定会在某些代码中发生 Guid
比较,在紧密循环中分配是可测量的。
现在,当然可以使 operator ==
使用 Equals(Guid)
,反之亦然,但将其复制和粘贴两次而不是一次确实没有任何额外的工作。