Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/276.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 检查==覆盖中是否存在null_C# - Fatal编程技术网

C# 检查==覆盖中是否存在null

C# 检查==覆盖中是否存在null,c#,C#,在下面的C代码片段中,我重写了=方法\u type是一个类型数short。所以我实际上是说两个WorkUnitTypes是相同的,而这两个shorts是相同的 public static bool operator ==(WorkUnitType type1, WorkUnitType type2) { if (type1 == null || type2 == null) return false; return type1._type == type2._ty

在下面的C代码片段中,我重写了
=
方法
\u type
是一个类型数
short
。所以我实际上是说两个
WorkUnitType
s是相同的,而这两个
short
s是相同的

public static bool operator ==(WorkUnitType type1, WorkUnitType type2)
{
    if (type1 == null || type2 == null)
        return false;
    return type1._type == type2._type;
}
因为R#警告我,
type1
/
type2
可能是空的,而且原因也很清楚,所以我试图用上面的
if
语句捕捉到这一点

现在我得到了一个
StackOverflowException
,它完全有意义,因为我实际上调用了覆盖

问题:如何将此方法写为“正确”。我如何抓住
type1
type2
可以
null
的情况


我的最佳猜测:也许我只是在这里误用了
=
,应该使用
等于
覆盖来检查相等性。但我仍然认为问题存在。那么,我的推理错误在哪里呢?

您正在寻找
ReferenceEquals()
函数,该函数将直接进行比较,绕过运算符重载。

除了SLaks所说的,如果两者都等于null,您可能还希望返回true。那么像这样,

public static bool operator ==(WorkUnitType type1, WorkUnitType type2)
{
    if (ReferenceEquals(type1, null))
        return ReferenceEquals(type2, null);

    if (ReferenceEquals(type2, null))
        return false;

    return type1._type == type2._type;
}

为完整起见:您还可以将这两个参数强制转换为
对象
。这将使用
对象
中定义的实现,而不是您的自定义实现

代码:

if ((object) type1 == null || (object) type2 == null)

我不知道
ReferenceEquals
存在。这实际上就是答案。谢谢