C#重载==

    public class TestABC
    {
        public int A = 0;
        public int B = 0;
        public static bool operator ==(TestABC a, TestABC b)
        {
            return true;
        }

        public static bool operator !=(TestABC a, TestABC b)
        {
            return false;
        }

        public override bool Equals(object obj)
        {
            return true;
        }

        public override int GetHashCode()
        {
            return 1;
        }

        public bool Equals(TestABC other)
        {
            if(other.A==A && other.B == B)
            {
                return true;
            }
            return false;
        }
    }

C# 对 == 的强制规则(必须同时满足)

只要你 重载 ==,你就 必须

1️⃣ 同时重载 !=

public static bool operator !=(TestABC a, TestABC b)
{
    return false;
}

否则 直接编译失败


2️⃣ 必须重写 Equals(object)GetHashCode()

否则编译器会警告 / 有时直接报错:

public override bool Equals(object obj)
{
    return base.Equals(obj);
}

public override int GetHashCode()
{
    return base.GetHashCode();
}

编译器在强制你:
== 与 Equals 语义必须一致


三、最小「不报错」版本(哪怕你 return true)

class TestABC
{
    public static bool operator ==(TestABC a, TestABC b)
    {
        return true;
    }

    public static bool operator !=(TestABC a, TestABC b)
    {
        return false;
    }

    public override bool Equals(object obj)
    {
        return true;
    }

    public override int GetHashCode()
    {
        return 1;
    }
}

⚠️ 注意
这只是“为了通过编译”,逻辑是灾难级的


四、正确的、规范的写法(你真正该用的)

class TestABC : IEquatable<TestABC>
{
    public int X;

    public static bool operator ==(TestABC? a, TestABC? b)
    {
        if (ReferenceEquals(a, b)) return true;
        if (a is null || b is null) return false;
        return a.Equals(b);
    }

    public static bool operator !=(TestABC? a, TestABC? b)
        => !(a == b);

    public bool Equals(TestABC? other)
        => other != null && X == other.X;

    public override bool Equals(object? obj)
        => Equals(obj as TestABC);

    public override int GetHashCode()
        => X.GetHashCode();
}

五、为什么 C# 这么“变态”地要求你这么多?

因为如果允许你只写:

a == b

但:

a.Equals(b)

是另一套逻辑,那:

  • Dictionary
  • HashSet
  • LINQ
  • WPF Binding

全部会崩

👉 编译器是在 替未来的你挡刀


六、一句直击你当前状态的判断

你现在这个 return true 写法,说明你在:

测试 operator 能不能进来 / 是否被调用

这是正常的探索阶段 👍
一旦写了 ==,你就必须把整个等值语义一次性写完整


七、如果你只是想“看看会不会进 ==”

👉 不要重载 ==

bool Same(TestABC a, TestABC b)
{
    return true;
}

八、你要不要我帮你判断?

你可以直接贴:

class TestABC
{
    ...
}
posted @ 2025-12-25 16:08  JohnYang819  阅读(4)  评论(0)    收藏  举报