c# - 在不使用 == 的情况下检查对象是否为 null

标签 c# object null overloading operation

在我的程序中,我有从 Dictionary 派生的对象。我需要检查 2 个对象是否相等,所以我做了一个重载运算符 ==。

但稍后,我需要检查对象是否为空。

If (object == null)  
{...}

所以此时,程序进入我定义的重载操作,但会抛出 NullReferenceException,因为要比较的对象之一为空。

所以在重载操作中,我需要检查一个对象是否为 null,但不使用 ==,因为那样会给我一个 StackOverflowException。

我该如何检查?

最佳答案

In my program, I have objects derived from Dictionary.

我会强烈地重新考虑首先从 Dictionary 派生。这很少是个好主意。总的来说,支持组合而不是继承,非常仔细考虑您希望平等(和哈希码)在面对可变数据时如何表现。如果两个对象在某一点相等而后来不相等,这通常是一个不好的迹象。

So at this point, the program goes into the overload operation I have defined, but will throw a NullReferenceException, since one of the objects to compare is null.

这就是问题所在。您重载的 == 运算符应该抛出异常 - 它应该将值与 null 进行比较。

通常 == 的重载看起来像这样:

public static bool ==(Foo left, Foo right)
{
    if (ReferenceEquals(left, right))
    {
        return true;
    }
    if (ReferenceEquals(left, null))
    {
        return false;
    }
    // Equals should be overridden, and should be handling the case where
    // right is null (by checking with ReferenceEquals too). Also consider
    // implementing IEquatable<Foo>
    return left.Equals(right);
}

在这里Object.ReferenceEquals用于执行引用身份比较。您可以在外部(在您当前正在考虑更改的代码中)使用它,但让 == 正确运行会更简洁。

关于c# - 在不使用 == 的情况下检查对象是否为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23786301/

相关文章:

php - Slim 3 getParsedBody() 始终为 null 和空

c# - 将各种数据一起发布的最佳方式(Web API)

c# - 请求.IsLocal

来自带有对象的对象的 AngularJS ng-options

java - 如何从文件中读取多个相同的对象

javascript - 将一个对象值设置为同一对象中的另一个值

mysql - 如何在 FUEL/ActiveRecord 中插入 NULL 值

c# - 将 IntPtr 指向的内存内容发送到 C# 上的 MemoryStream 变量

c# - 加速插入 - 一次插入列表