C# 检查==覆盖中是否存在null
在下面的C代码片段中,我重写了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
=
方法\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
存在。这实际上就是答案。谢谢