填充字典中的KeyNotFoundException

时间:2012-07-19 10:01:26

标签: c# dictionary compare keynotfoundexception

我正在尝试修改字典中的值,但编译器会抛出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;
            }
        }
}

为什么编译器在字典中拒绝键时会有什么想法?

2 个答案:

答案 0 :(得分:3)

是。你还没有覆盖GetHashCode。

答案 1 :(得分:0)

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