c# - ReferenceEquals() 的合法使用

标签 c# .net pointers collections reference

在按照声明式风格编写的 .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/

相关文章:

c# - 在多个名称迭代器上移动下一个

c# - 意外的字符串总和

c# - 使用客户端证书时,大型 POST 请求会导致 Asp.Net Web API 超时

c# - 绑定(bind)到集合的 View 并在 WPF 中调用 ToString()

.net - 作为项目经理,了解 .net 最重要的事情是什么?

C 的未定义行为

c - c中的指针和结构

C#.NET 3.5 : How to invoke an event handler and wait for it to complete

c# - 制作智能感知/自动完成列表时过滤字符串列表的最快方法是什么?

c# - 在 C# 中保留 C++ 指针是否安全?