我有一个班级Room
和一个班级World
。目前,我有一个
Dictionary<Point, Room> world;
我将Room
存储起来如下:
world.Add(new Point(0,0), new Room());
但是当我尝试访问它时,它返回null:
world.Get(new Point(0,0));
我理解为什么会这样。但我的问题是:有人知道更好的方法吗?
答案 0 :(得分:8)
如果您的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版本。
答案 1 :(得分:1)
实例化字典时可以provide your own IEqualityComparer:
public Dictionary(IEqualityComparer<TKey> comparer)
即使你不能修改原始的TKey类,这也有效。