你好,我想修改字典中的值,但編譯器拋出KeyNotFoundException
。我敢肯定,我在字典中聲明瞭這個關鍵字,因爲我打電話給GenerateEmptyChunks()
方法,該方法使用塊的填充字典填充字典的位置,並且值爲電平生成器的值。我檢查了debuger,並且Chunks
字典對象正確地填充了鍵和值。它是由我的不合作CompareTo
方法引起的嗎?如果是,我如何修改CompareTo
方法來返回正確的值?KeyNotFoundException在填充dictonary
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;
}
}
}
任何想法,爲什麼被拒絕的編譯器按鍵,當他們在字典嗎?
謝謝,它的工作原理。 – 2012-07-19 10:15:04