简体   繁体   English

这种使用ReferenceEquals的方式正确吗

[英]Is this way of using ReferenceEquals correct

I am doing some code review and I stopped on the following construct. 我正在做一些代码审查,并停止了以下结构。 Is this the Correct way of using ReferenceEquals to check if a method returned actually the same object that was passed as an argument or a new one? 这是使用ReferenceEquals来检查某个方法返回的实际上是否与作为参数传递的对象或新参数相同的对象的正确方法吗?

int x = 5;
Foo f = new Foo()

Foo DoSomething(Foo f)
{
    if(x > 5)
    {
         return f;
    }
    else
    {
        return new Foo();
    }
}

Foo ff = DoSomething(f);

if(Object.ReferenceEquals(ff, f))
{
    //do something
}

Yes for reference types. 是,对于引用类型。 Value types bit complicated as they are boxed before passing to the method. 值类型在传递给方法之前先进行装箱,这有点复杂。

When comparing value types. 比较值类型时。 If objA and objB are value types, they are boxed before they are passed to the ReferenceEquals method. 如果objA和objB是值类型,则将它们装箱,然后将它们传递给ReferenceEquals方法。 This means that if both objA and objB represent the same instance of a value type, the ReferenceEquals method nevertheless returns false, 这意味着,如果objA和objB都代表值类型的相同实例,则ReferenceEquals方法仍然返回false,

Read more details here 在此处阅读更多详细信息

Reference equality of value types 值类型的引用相等

ReferenceEquals Method - MSDN ReferenceEquals方法-MSDN

Unlike the Equals method and the equality operator, the ReferenceEquals method cannot be overridden. 与Equals方法和equals运算符不同,ReferenceEquals方法不能被覆盖。 Because of this, if you want to test two object references for equality and are unsure about the implementation of the Equals method, you can call the ReferenceEquals method. 因此,如果您要测试两个对象引用是否相等并且不确定Equals方法的实现,则可以调用ReferenceEquals方法。 However, note that if objA and objB are value types, they are boxed before they are passed to the ReferenceEquals method. 但是,请注意,如果objA和objB是值类型,则在将它们传递给ReferenceEquals方法之前将它们装箱。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM