c# - 重载 == 运算符抛出带有非空操作数的 NullReferenceException

标签 c# iequatable

我正在尝试实现 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 == nullEquals(TestClass)调用相等运算符,它调用 Equals(TestClass) ——无限循环。第二轮,other为空,这导致 NullReferenceException当您将其作为 left 传递给相等运算符时参数。

你应该使用 ReferenceEquals(other, null)other is null相反。

关于c# - 重载 == 运算符抛出带有非空操作数的 NullReferenceException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52457952/

相关文章:

c# - ASPX 似乎无法找到我的代码隐藏文件?

javascript - 在决定输入字段的类型之前检查浏览器是否兼容 HTML5

c# - IEquatable 中断 Entity Framework 实体的加载

c# - 当 ==、CompareTo() 和 Equals() 不一致时会发生什么?

c# - GetHashCode() 返回值应该基于原始对象的状态还是修改后的对象的状态?

swift - 在可哈希类中自动实现唯一 ID

c# - 使用: “not all code paths return a value” 方法获取编译错误

c# - 系统状态 C# 的函数

c# - 最新的 VS Mac 更新导致 Xamarin Android 中的 SetContentView(resourceid) 出现 SIGSEGV

c# - 使用 IEquatable<T> 测试对象集合的相等性