gpt4 book ai didi

c# - 填充字典中的 KeyNotFoundException

转载 作者:行者123 更新时间:2023-11-30 22:26:51 24 4
gpt4 key购买 nike

我正在尝试修改字典中的值,但编译器抛出 KeyNotFoundException。我敢肯定,我在字典中声明了该键,因为我正在调用 GenerateEmptyChunks() 方法,该方法用具有其位置键的 block 填充字典,并且对于关卡生成器而言值为空。我检查了调试器,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() 由关卡生成器为每个图 block 调用的方法:

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。

关于c# - 填充字典中的 KeyNotFoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11558380/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com