C#坐标键控字典

我有一个班级
Room
,班级
World
。目前,我有一个
    Dictionary<Point, Room> world;
我存储
Room
s就像这样:
    world.Add(new Point(0,0), new Room());
但是当我尝试访问它时,它返回null:
    world.Get(new Point(0,0));
我理解为什么会这样。但我的问题是:有人知道更好的方法吗?     
已邀请:
如果您的
Point
实现正确实现
GetHashCode
Equals
,那应该可以正常工作。 例如,以下工作完美:
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();
    }
}
这是使用System.Drawing.Point,正确实现
GetHashCode
。 (按预期打印“2”。) 我怀疑问题是你实施的
Point
。确保它正确实现
Equals
GetHashCode
,或者(更好)使用框架中包含的Point版本。     
在实例化字典时,您可以提供自己的IEqualityComparer:
public Dictionary(IEqualityComparer<TKey> comparer)
即使您无法修改原始TKey类,这也有效。     

要回复问题请先登录注册