gpt4 book ai didi

c# - ReferenceEquals() 的合法使用

转载 作者:太空狗 更新时间:2023-10-29 19:51:37 26 4
gpt4 key购买 nike

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com