在按照声明式风格编写的 .NET 程序中,ReferenceEquals() 有哪些合法用途?
最佳答案
不确定“按照声明式编写”是什么意思,但是 ReferenceEquals
通常在覆盖 ==
运算符时使用。来自 http://msdn.microsoft.com/en-us/library/ms173147.aspx :
public static bool operator ==(ThreeDPoint a, ThreeDPoint b)
{
// If both are null, or both are same instance, return true.
if (System.Object.ReferenceEquals(a, b))
{
return true;
}
// If one is null, but not both, return false.
if (((object)a == null) || ((object)b == null))
{
return false;
}
// Return true if the fields match:
return a.x == b.x && a.y == b.y && a.z == b.z;
}
请务必查看下面的注意以了解理由:
Note: A common error in overloads of operator == is to use (a == b), (a == null), or (b == null) to check for reference equality. This instead creates a call to the overloaded operator ==, causing an infinite loop. Use ReferenceEquals or cast the type to Object, to avoid the loop.
关于c# - ReferenceEquals() 的合法使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9910996/