英文:
Why is this class not comparing equal to a string when it should?
问题
以下是您提供的代码的翻译:
[System.Serializable]
public sealed class TilemapID
{
public static readonly string[] ID_LIST = new string[] { "base", "foreground", "background" };
public string id;
public TilemapID(string id)
{
this.id = id;
}
public override string ToString()
{
return id;
}
public override int GetHashCode()
{
return id.GetHashCode();
}
public override bool Equals(object obj)
{
return id.Equals(obj);
}
public static explicit operator string(TilemapID id) => id.id;
public static explicit operator TilemapID(string s)
{
for (int i = 0; i < ID_LIST.Length; i++)
{
if (ID_LIST[i].Equals(s))
return new TilemapID(ID_LIST[i]);
}
return null;
}
}
请注意,我只提供了代码的翻译部分,不包括问题的回答。
英文:
I have a class that essentially wraps a string so that I can make a custom editor for this class easily. I want this class to act as if it is a string when comparing to other classes. I am using this class as a key in a Dictionary, yet when using the TryGetKey method it returns false even when both TilemapID's id strings are the same.
This is what I have:
[System.Serializable]
public sealed class TilemapID
{
public static readonly string[] ID_LIST = new string[] { "base", "foreground", "background" };
public string id;
public TilemapID(string id)
{
this.id = id;
}
public override string ToString()
{
return id;
}
public override int GetHashCode()
{
return id.GetHashCode();
}
public override bool Equals(object obj)
{
return id.Equals(obj);
}
public static explicit operator string(TilemapID id) => id.id;
public static explicit operator TilemapID(string s)
{
for (int i = 0; i < ID_LIST.Length; i++)
{
if (ID_LIST[i].Equals(s))
return new TilemapID(ID_LIST[i]);
}
return null;
}
}
I can verify through the Visual Studio Debugger that both this "id" and another TilemapID's "id" are the same:
Both maps[q].id & savedTiles[0].id are the same.
I've tried to step through visual studio with the debugger, and when it gets to the part shown in the screenshot it goes to the GetHashCode method, then the Equals method, which returns false, so it skips over grabbed = g
and goes to else continue
. Shouldn't it actually go to grabbed = g
because I overrode the Equals and GetHashCode methods, which should return true?
答案1
得分: -1
以下是要翻译的内容:
由于我将我的类用作字典中的键,当我尝试使用此类的实例访问值时,它将不等于任何键。将Equals方法更改为以下内容可以解决该问题:
public override bool Equals(object obj)
{
return id == obj.ToString();
}
英文:
Since I was using my class as a key in a dictionary, when I would try to access a value with an instance of this class it would not be equal to any keys. Changing the Equals method to this fixes that problem:
public override bool Equals(object obj)
{
return id == obj.ToString();
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论