已填充字典中出现KeyNotFoundException



我试图修改字典中的值,但编译器抛出KeyNotFoundException。我确信,我在dictionary中声明了该键,因为我调用的是GenerateEmptyChunks()方法,该方法用其位置的键填充dictionary,并且级别生成器的值为空。我已经检查了调试器,并且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;
            }
        }
}

有什么想法吗?当关键字在字典里的时候,编译器为什么拒绝它们?

是。您尚未覆盖GetHashCode。

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

相关内容

  • 没有找到相关文章

最新更新