KeyNotFoundException in filled dictionary(填充字典中的 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:填充字典中的 KeyNotFoundException


基础教程推荐
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01