这种使用 ReferenceEquals 的方式是否正确
Is this way of using ReferenceEquals correct
我正在做一些代码审查,我停止了以下构造。这是使用 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
}
对于引用类型是的。值类型有点复杂,因为它们在传递给方法之前被装箱。
When comparing value types. If objA and objB are value types, they are
boxed before they are passed to the ReferenceEquals method. This means
that if both objA and objB represent the same instance of a value
type, the ReferenceEquals method nevertheless returns false,
阅读更多详情here
Reference equality of value types
Unlike the Equals method and the equality operator, the ReferenceEquals method cannot be overridden. 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. However, note that if objA and objB are value types, they are boxed before they are passed to the ReferenceEquals method.
我正在做一些代码审查,我停止了以下构造。这是使用 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
}
对于引用类型是的。值类型有点复杂,因为它们在传递给方法之前被装箱。
When comparing value types. If objA and objB are value types, they are boxed before they are passed to the ReferenceEquals method. This means that if both objA and objB represent the same instance of a value type, the ReferenceEquals method nevertheless returns false,
阅读更多详情here
Reference equality of value types
Unlike the Equals method and the equality operator, the ReferenceEquals method cannot be overridden. 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. However, note that if objA and objB are value types, they are boxed before they are passed to the ReferenceEquals method.