C#坐标键控字典

时间:2011-01-15 00:54:05

标签: c# multidimensional-array coordinate

我有一个班级Room和一个班级World。目前,我有一个

    Dictionary<Point, Room> world;

我将Room存储起来如下:

    world.Add(new Point(0,0), new Room());

但是当我尝试访问它时,它返回null:

    world.Get(new Point(0,0));

我理解为什么会这样。但我的问题是:有人知道更好的方法吗?

2 个答案:

答案 0 :(得分:8)

如果您的Point实施正确实施GetHashCodeEquals,这应该可以正常工作。

例如,以下内容完美无缺:

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的实施。确保它正确实现EqualsGetHashCode,或者(更好)使用框架中包含的Point版本。

答案 1 :(得分:1)

实例化字典时可以provide your own IEqualityComparer

public Dictionary(IEqualityComparer<TKey> comparer)

即使你不能修改原始的TKey类,这也有效。