gpt4 book ai didi

C# - 无法覆盖 ==

转载 作者:行者123 更新时间:2023-11-30 13:53:56 24 4
gpt4 key购买 nike

我有以下类(class)(为 Unity 游戏引擎构建)

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);
}
}

当我尝试进行测试时,函数 Equals 似乎可以正常工作,但运算符 == 给了我不同的结果。

    [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

}

我的实现是否有问题?

更新:这是完整的类(class),以防有所不同:https://www.hastebin.com/divazubero.cpp

最佳答案

问题是你的变量类型是ScriptableObject , 不是 Biome 类型.

编译器必须在编译时决定调用哪个重载。并且由于它在编译时不知道运行时类型将是 Biome , 它会调用 == ScriptableObject 的运营商.
如果该类没有重写 ==运算符,object 的运算符被调用(它做了一个简单的 ReferenceEquals 这当然是 false )。

==运算符重载不是 virtual .

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

关于C# - 无法覆盖 ==,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50686081/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com