实体框架 4 中的 !(ReferenceEquals()) 与 !=
除非类专门重写为 Object 定义的行为,否则 ReferenceEquals 和 == 会执行相同的操作事情...比较参考文献。
在属性设置器中,我通常使用该模式
private MyType myProperty;
public MyType MyProperty
{
set
{
if (myProperty != value)
{
myProperty = value;
// Do stuff like NotifyPropertyChanged
}
}
}
但是,在实体框架生成的代码中,将 if
语句替换为
if (!ReferenceEquals(myProperty, value))
使用 ReferenceEquals 更明确(因为我猜不是所有 C# 程序员都知道 == 确实如果不被覆盖,则相同)。
我没有注意到这两个 if 变体之间有什么区别吗?他们是否考虑到了 POCO 设计者可能重写 ==
的可能性?
简而言之,如果我没有覆盖 ==
,我是否可以使用 != 而不是 ReferenceEquals()
来保存?
Unless a class specifically overrides the behavior defined for Object, ReferenceEquals and == do the same thing... compare references.
In property setters, I have commonly used the pattern
private MyType myProperty;
public MyType MyProperty
{
set
{
if (myProperty != value)
{
myProperty = value;
// Do stuff like NotifyPropertyChanged
}
}
}
However, in code generated by Entity Framework, the if
statement is replaced by
if (!ReferenceEquals(myProperty, value))
Using ReferenceEquals is more explicit (as I guess not all C# programmers know that == does the same thing if not overridden).
Is there any difference that's escaping me between the two if-variants? Are they perhaps accounting for the possibility that POCO designers may have overridden ==
?
In short, if I have not overridden ==
, am I save using != instead of ReferenceEquals()
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
以下是不同的语义:
ReferenceEquals()
。object.Equals()
==()
仅适用于不可变类型。然后用它来测试相等性。当然,相反的对应物也是相应的意思。
这里是一个摘要
Here are the different semantics:
ReferenceEquals()
must be used if you mean that the objects are exactly the same (identity check).object.Equals()
shall be used if you mean the objects have the same value (equality check)==()
shall only be used for immutable types. Then use it to test for equality.Of course the inversed counterparts are meant accordingly.
Here is a summary
== 应该测试引用是否指向相同的位置,而 ReferenceEquals 应该测试它们是否包含相同的数据
== should test to see if the reference points to the same location whereas ReferenceEquals tests to see if they contain the same data