C# - Can't override ==

时间:2018-06-04 17:44:09

标签: c# unity3d operator-overloading override iequatable

I have the following class (built for Unity Game Engine)

using System;
using System.Collections.Generic;
using UnityEngine;

public class Biome : ScriptableObject, IEquatable<Biome>
{
    // ...

    //
    // IEquatable
    //

    public bool Equals(Biome other)
    {
        if (other == null)
            return false;

        return this.name == other.name;
    }

    public override bool Equals(object obj)
    {
        if (obj == null) return false;

        Biome other = obj as Biome;

        if (other == null) return false;

        return Equals(other);
    }

    public override int GetHashCode()
    {
        return this.name.GetHashCode();
    }

    public static bool operator ==(Biome biome1, Biome biome2)
    {
        if (object.ReferenceEquals(biome1, biome2)) return true;
        if (object.ReferenceEquals(null, biome1)) return false;
        if (object.ReferenceEquals(null, biome2)) return false;

        return biome1.Equals(biome2);
    }

    public static bool operator !=(Biome biome1, Biome biome2)
    {
        if (object.ReferenceEquals(biome1, biome2)) return false;
        if (object.ReferenceEquals(biome1, null)) return true;
        if (object.ReferenceEquals(biome2, null)) return true;

        return !biome1.Equals(biome2);
    }
}

When I try to do test, the function Equals seems to be working, but the operator == gives me a different result.

    [Test]
    public void FooTest()
    {
        ScriptableObject biome1 = ScriptableObject.CreateInstance("Biome");
        ScriptableObject biome2 = ScriptableObject.CreateInstance("Biome");

        biome1.name = "Biome #1";
        biome2.name = "Biome #1";

        Assert.IsTrue(biome1.Equals(biome2));
        Assert.IsTrue(biome1 == biome2);  // This one fails

    }

Am I doing something wrong with my implementation?

UPDATE: Here is the full class, in case it makes a difference: https://www.hastebin.com/divazubero.cpp

1 个答案:

答案 0 :(得分:8)

问题是您的变量属于ScriptableObject类型,而不属于Biome类型。

编译器必须在编译时决定调用哪个重载。由于它在编译时不知道运行时类型为Biome,因此它会触发对== ScriptableObject运算符的调用。
如果该类没有被覆盖的==运算符,则调用object的运算符(执行简单的ReferenceEquals,当然false)。< / p>

==运算符重载 virtual

如果您在测试中使用特定的类型Biome,它将按预期工作。