填充字典中的KeyNotFoundException

编程入门 行业动态 更新时间:2024-10-18 10:16:30
本文介绍了填充字典中的KeyNotFoundException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我试图修改字典中的值,但是编译器抛出KeyNotFoundException.我敢肯定,我在字典中声明了该键,因为我正在调用GenerateEmptyChunks()方法,该方法用具有其位置键的块填充字典,并且级别生成器的值是空的.我已经检查了调试器,并且Chunks字典对象正确地填充了键和值.是我无法使用CompareTo方法造成的吗?如果是,我如何修改CompareTo方法以返回正确的值?

I am trying to modify value in dictionary, but the compiler throws KeyNotFoundException. I'm sure, I declared that key in dictionary, because I am calling GenerateEmptyChunks() method, which fills dictionary with chunks with key of their position and values are empty for level generator. I've checked debugger and Chunks dictionary object is correctly filled with keys and values. Is it caused by my unworking CompareTo method? If yes, how I have modify CompareTo method to return right values?

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()方法,该方法由关卡生成器为每个图块调用:

AddBlock() method which is called by level generator for each tile:

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; } } }

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

Any ideas why is compiler rejecting keys, when they are in dictionary?

推荐答案

是.您尚未覆盖GetHashCode.

Yes. You have not overridden GetHashCode.

更多推荐

填充字典中的KeyNotFoundException

本文发布于:2023-11-06 14:05:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1563895.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字典   KeyNotFoundException

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!