gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 13:16:48 25 4
gpt4 key购买 nike

在我的程序中,我有从 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com