2010-08-23 110 views
0

请比较这两个代码。我不明白为什么前者不工作而后者完美工作。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; 
    } 
} 
+0

你也应该发布你的Location类,并在这里看看 - > http://stackoverflow.com/questions/634826/using-an-object-as-a-generic-dictionary-key-in-net ;) – digEmAll 2010-08-23 06:58:48

+0

这就是正确的...你也应该发布位置类。位置类的标识符成员是字符串还是其他东西? – Shekhar 2010-08-23 07:03:14

+0

@digEmAll - 感谢您的链接。它解决了我的问题。 – 2010-08-23 09:33:37

回答

3

也不应该工作,除非你在Location类中重写EqualsGetHashCode使得Dictionary匹配基于其标识的平等,而不是对象相等Location关键对象。

0

请问位置类实现的GetHashCode?如果没有,你应该覆盖这个,并确保它为每个实例返回一个唯一的int。

+0

感谢您的提示。实现了GetHashCode和Equals。现在是工作。 – 2010-08-23 09:34:20

-1

你提到的代码段都不起作用。尝试再次运行标记为“工作版本”的代码,它应该抛出与第一个相同的异常。

0

除了GetHashCode,当需要报告散列码相等时,您需要覆盖Equals,以得出对象相等的结论。隔离哈希码只能证明不平等。不相等的对象可以有相同的散列码;相同的哈希码不能证明对象是相等的。

+0

感谢您的提示。实现了GetHashCode和Equals。现在是工作。 – 2010-08-23 09:35:11