簡體   English   中英

C#對象作為字典鍵問題

[英]C# Object as Dictionary Key Problem

請比較這兩個代碼。 我不明白為什么前一個不能正常工作而后一個卻不能正常工作。

// 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類中重寫EqualsGetHashCode ,否則Dictionary都不應該根據其標識符的相等性而不是對象的相等性來匹配Location鍵對象,否則兩者都不起作用。

Location類是否實現GetHashCode? 如果不是,則應重寫此方法並確保它為每個實例返回唯一的int。

除了GetHashCode之外,您還需要重寫Equals,以得出對象相等的結論,即當哈希碼被報告為相等時調用它。 孤立地,哈希碼只能證明不平等。 不相等的對象可以具有相等的哈希碼; 相等的哈希碼不能證明對象相等。

您提到的兩個代碼段均無效。 嘗試再次運行標記為“工作版本”的代碼,它應引發與第一個相同的異常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM