【Unity + C#】键为类的字典的问题

问题

  • 我有一个类,这个类由一个枚举类型和一个 int 组成
[Serializable]
public enum TerrainType
{
    
    
    Player = -1, Empty = 0, Wall = 1, Coin, Gem, Flower, Goal, Spike, Belt, TurnBelt, Lever, Door, Key, Portal, Rock,
}
[Serializable]
public class TerrainUnit
{
    
    
    public TerrainType Type;
    public int State;
}
  • 我创建了一个字典,键即为 TerrainUnit,值为 Sprite
    Dictionary<TerrainUnit, Sprite> Dict
  • 我在调用时,发现这个问题:
    这里假设 A,B,X 为一个具体的对应类型的内容。
	TerrainUnit tu = new TerrainUnit();
    tu.Type = A;
    tu.State = B;
    Dict[tu] = X;
    
    TerrainUnit tu = new TerrainUnit();
    tu.Type = A;
    tu.State = B;
    Y = Dict[tu]
  • 然后出错,找不到键为tu的值
    WTF,为啥?

错误原因

  • 首先,Dictionary 为哈希表,SortedDictionary 为有序字典
    这里的哈希表,由于实例不同,尽管实例里面的这俩属性的值相同,但获得的哈希值不同了

使用 Dictionary 进行修改

  • 既然是哈希表,那么我们重写获得的哈希值和比较函数即可
[Serializable]
public class TerrainUnit
{
    
    
    public TerrainType Type;
    public int State;
	// 重写比较函数
    public override bool Equals(object obj)
    {
    
    
        TerrainUnit other = obj as TerrainUnit;
        int x1 = GetHashCode();
        int x2 = other.GetHashCode();
        return x1 == x2;
    }
	// 重写哈希值
    public override int GetHashCode()
    {
    
    
        return ((int)Type) * 100 + State;
    }
}

使用 SortedDictionary 进行修改

  • 既然是一个字典,那么我们需要重写比较函数
[Serializable]
public class TerrainUnit : IComparable	// 注意这里需要继承这个比较接口
{
    
    
    public TerrainType Type;
    public int State;
    // 写一下比较函数,注意函数的返回类型需要是 int
    // -1 表示目前的小,0 表示相同,1 表示目前的大
    public int CompareTo(object obj)
    {
    
    
        TerrainUnit other = obj as TerrainUnit;
        if (other == null) return 1;
        if (Type != other.Type)
        {
    
    
            if (Type < other.Type) return -1;
            return 1;
        }
        if (State != other.State)
        {
    
    
            if (State < other.State) return -1;
            return 1;
        }
        return 0;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_45775438/article/details/128526036