我正在尝试实现 IEquatable<T>
接口(interface)和==
运算符(operator)。下面的实现触发了 NullReferenceException
当我尝试使用 ==
运算符,尽管两个操作数都是非空的。我在最小示例代码中添加了注释,以准确显示异常发生的位置。我做错了什么?
using System;
namespace scratchpad
{
class TestClass : IEquatable<TestClass>
{
public int data;
public TestClass(int d)
{
this.data = d;
}
public bool Equals(TestClass other)
{
if (other == null)
return false;
else
return this.data == other.data;
}
public override bool Equals(object other)
{
if (other is TestClass)
return this.Equals((TestClass)other);
else //Includes null
return false;
}
public override int GetHashCode()
{
return this.data;
}
public static bool operator ==(TestClass left, TestClass right)
{
return left.Equals(right); //This line triggers the NullReferenceException
}
public static bool operator !=(TestClass left, TestClass right)
{
return !left.Equals(right);
}
}
class Program
{
static void Main(string[] args)
{
TestClass tc1 = new TestClass(10);
TestClass tc2 = new TestClass(10);
Console.WriteLine("tc1="+tc1.data); //Prints "tc1.data=10" fine
Console.WriteLine("tc1="+tc1.data); //Prints "tc2.data=10" fine
bool isEqual = tc1 == tc2; //NullReferenceException occur here
Console.WriteLine("isEqual="+isEqual); //Never gets to here
}
}
}
编辑(澄清问题以回应重复的问题标志):
我不是在问什么 NullReferenceException
是(我明白)而且我对 ReferenceEquals
不感兴趣因为我需要使对象的值相等。
最佳答案
行other == null
在 Equals(TestClass)
调用相等运算符,它调用 Equals(TestClass)
——无限循环。第二轮,other
为空,这导致 NullReferenceException
当您将其作为 left
传递给相等运算符时参数。
你应该使用 ReferenceEquals(other, null)
或 other is null
相反。
关于c# - 重载 == 运算符抛出带有非空操作数的 NullReferenceException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52457952/