实体框架 4 中的 !(ReferenceEquals()) 与 !=

发布于 2024-09-05 08:02:53 字数 781 浏览 1 评论 0原文

除非类专门重写为 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦幻的心爱 2024-09-12 08:02:53

以下是不同的语义:

  • 如果您的意思是对象完全相同(身份检查),则必须使用 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

层林尽染 2024-09-12 08:02:53

== 应该测试引用是否指向相同的位置,而 ReferenceEquals 应该测试它们是否包含相同的数据

== should test to see if the reference points to the same location whereas ReferenceEquals tests to see if they contain the same data

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文