请比较这两个代码。我不明白为什么前者不工作而后者完美工作。C#对象作为字典键问题
// With loop - not work
for (int i = 0; i < 5; i++)
{
Location l = new Location();
l.Identifier = i.ToString();
_locations.Add(l);
}
////
Dictionary<Location, Route> _paths = new Dictionary<Location, Route>();
foreach (Location loc in _locations)
{
_paths.Add(loc, new Route(loc.Identifier));
}
Location start = new Location();
start.Identifier = "1";
_paths[start].Cost = 0; //raised Key not exists error
这里是工作的版本...
// Without Loop - it work
Location l1 = new Location();
l1.Identifier = "1";
_locations.Add(l1);
Location l2 = new Location();
l2.Identifier = "2";
_locations.Add(l2);
Location l3 = new Location();
l3.Identifier = "3";
_locations.Add(l3);
/////
Dictionary<Location, Route> _paths = new Dictionary<Location, Route>();
foreach (Location loc in _locations)
{
_paths.Add(loc, new Route(loc.Identifier));
}
Location start = new Location();
start.Identifier = "1";
_paths[start].Cost = 0;
任何想法?谢谢。
编辑:位置类
public class Location
{
string _identifier;
public Location()
{
}
public string Identifier
{
get { return this._identifier; }
set { this._identifier=value; }
}
public override string ToString()
{
return _identifier;
}
}
你也应该发布你的Location类,并在这里看看 - > http://stackoverflow.com/questions/634826/using-an-object-as-a-generic-dictionary-key-in-net ;) – digEmAll 2010-08-23 06:58:48
这就是正确的...你也应该发布位置类。位置类的标识符成员是字符串还是其他东西? – Shekhar 2010-08-23 07:03:14
@digEmAll - 感谢您的链接。它解决了我的问题。 – 2010-08-23 09:33:37