C# coordinate keyed dictionary
I have a class Room
, and a class Wor开发者_JAVA技巧ld
. Currently, I have a
Dictionary<Point, Room> world;
which I store Room
s in like so:
world.Add(new Point(0,0), new Room());
But when I try to access it, it returns null:
world.Get(new Point(0,0));
I understand the reason why this is happening. But my question is: Does anybody know a better way of doing this?
That should work fine, provided your Point
implementation implements GetHashCode
and Equals
properly.
For example, the following works perfectly:
using System;
using System.Collections.Generic;
using System.Drawing;
class Room
{
public int X
{
get;
set;
}
}
struct Program
{
static void Main()
{
Dictionary<Point, Room> world = new Dictionary<Point, Room>();
world.Add(new Point(0, 0), new Room() { X = 0 });
world.Add(new Point(2, 3), new Room() { X = 2 });
Room room = world[new Point(2, 3)];
Console.WriteLine(room.X);
Console.ReadKey();
}
}
This is using System.Drawing.Point, which implements GetHashCode
properly. (It prints "2", as expected.)
I suspect the problem is your implementation of Point
. Make sure it implements Equals
and GetHashCode
correctly, or (better yet) use a version of Point included in the framework.
You can provide your own IEqualityComparer when you instantiate the dictionary:
public Dictionary(IEqualityComparer<TKey> comparer)
This works even if you can't modify the original TKey class.
精彩评论