【发布时间】:2013-04-02 05:40:15
【问题描述】:
好的,我有一个类,我想在其中覆盖相等运算符,所以我有以下代码:
/// <summary>
/// Over-ride of the equality operator.
/// </summary>
/// <param name="credential1">The left hand object to test for equality.</param>
/// <param name="credential2">The right hand object to test for equality.</param>
/// <returns>True if the objects are equal.</returns>
public static bool operator ==(KnownServerCredential credential1, KnownServerCredential credential2)
{
// ok check if either is null
bool cell1Null = Equals(null, credential1);
bool cell2Null = Equals(null, credential2);
// if both are, then it's true
if (cell1Null && cell2Null)
{
return true;
}
// if only one is, then how can they be the same?
if (cell1Null || cell2Null)
{
return false;
}
// neither are - so we can now go to full on equality
return credential1.IsEqualTo(credential2);
}
这很好用,我很满意。然而,静态分析工具(Resharper 和 VS2010 代码分析)发誓最后一行可能会引发空引用异常,因为我在前两行中检查空值的方式。如果我将前两行从Equals(null, credentialX) 更改为credentialX == null,那么静态分析工具会很高兴,但它会创建堆栈溢出异常,因为我会递归调用相等覆盖。使用(object)credentialX == null 可以两全其美,但这似乎不是最干净的方式。
所以简单的问题是,我是否遗漏了什么,或者演员和比较是实现我正在寻找的最佳方式?
【问题讨论】:
-
Object.ReferenceEquals 可能有用吗?
-
请不要忘记
.GetHashCode()! -
@AndreasNiedermair 他没有覆盖
Equals,所以覆盖GetHashCode是不正确的 -
@MarcGravell 如果 OP 没有覆盖
.Equals- 是的......但我认为(我在这里想到了一个孤立的例子......) - 谢谢......不幸的是 6 分钟,所以我无法添加此作为澄清,但我认为您的评论就足够了! -
对不起,我不想把整个班级都包括在内,因为我已经超越了两者,我确实理解其中的含义,我只是想知道最好的风格特别的小实例:)