2

我正在尝试修改字典中的值,但编译器会抛出KeyNotFoundException. 我敢肯定,我在字典中声明了该键,因为我正在调用GenerateEmptyChunks()方法,该方法用具有位置键的块填充字典,而关卡生成器的值是空的。我检查了调试器和Chunks字典对象是否正确填充了键和值。CompareTo是我不工作的方法造成的吗?如果是,我如何修改CompareTo方法来返回正确的值?

public Dictionary<WPoint, WChunk> Chunks = new Dictionary<WPoint, WChunk>();

GenerateEmptyChunks()方法:

public void GenerateEmptyChunks(int Xcount, int Ycount)
    {
        for(int x = 0; x <= Xcount; x++)
        {
            for (int y = 0; y <= Ycount; y++)
            {
                this.Chunks.Add(new WPoint(x, y), new WChunk(x, y));
            }
        }
    }

AddBlock()方法由每个图块的级别生成器调用:

public void AddBlock(WPoint location, int data)
    {
        this.Chunks[location.GetChunk()].AddTile(new WTile(location, data));
    }

Wchunk对象:

public class WChunk
    {
        public int ChunkX;
        public int ChunkY;
        public SortedDictionary<WPoint, WTile> Tiles = new SortedDictionary<WPoint, WTile>();

        public WChunk(int posX, int posY)
        {
            ChunkX = posX;
            ChunkY = posY;
        }

        public void AddTile(WTile tile)
        {
            Tiles.Add(tile.GetLocation(), tile);
        }
    }

WPoint对象:

public class WPoint : IComparable
    {
        public float X;
        public float Y;

        public WPoint(float x, float y)
        {
            X = x;
            Y = y;
        }

        public WPoint GetChunk()
        {
            //Oprava pre bloky mensie ako (1,1)
            if (X <= 16 && Y <= 16)
            {
                return new WPoint(0, 0);
            }
            else
            {
                double pX = (double)(X / 16);
                double pY = (double)(Y / 16);
                return new WPoint((int)Math.Floor(pX), (int)Math.Floor(pY));
            }
        }

        public int CompareTo(object obj)
        {
            WPoint point2 = (WPoint)obj;
            if (point2.X == this.X && point2.Y == this.Y)
            {
                return 0;
            }
            else if (point2.X >= this.X && point2.Y >= this.Y)
            {
                return -1;
            }
            else
            {
                return 1;
            }
        }
}

任何想法为什么编译器拒绝键,当它们在字典中时?

4

2 回答 2

3

是的。您尚未覆盖 GetHashCode。

于 2012-07-19T10:08:44.697 回答
0

Dictionary 使用 GetHashCode 和 Equals 进行键比较,因此实现 IComparable 接口是不够的。看看这个答案,这正是你所需要的。

于 2012-07-19T10:10:18.877 回答