我有一堂课Room
,一堂课World
。目前,我有一个
Dictionary<Point, Room> world;
Room
我像这样存储s:
world.Add(new Point(0,0), new Room());
但是当我尝试访问它时,它返回 null:
world.Get(new Point(0,0));
我理解发生这种情况的原因。但我的问题是:有人知道这样做的更好方法吗?
我有一堂课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();
}
}
这是使用GetHashCode
正确实现的 System.Drawing.Point。(它按预期打印“2”。)
我怀疑问题出在您的Point
. 确保它正确实现Equals
,GetHashCode
或者(更好)使用框架中包含的 Point 版本。
您可以在实例化字典时提供自己的 IEqualityComparer :
public Dictionary(IEqualityComparer<TKey> comparer)
即使您无法修改原始 TKey 类,这也有效。