2011-05-25 67 views
2

我的問題是ContainsKey總是返回false,即使他們的鍵已被添加和.Equals計算結果爲true。C#字典ContainsKey

我有下面的類:然後有一個字典,看起來像這樣

public class StatisticsFilter 
{ 
    private String someString1; 
    private String someString2; 
    ..... 

    public override string ToString() 
    { 
     return string.Format("{0}-{1}-{2}-{3}-{4}", someString1, someString2, ...) 
    } 

    public override bool Equals(object obj) 
    {    
     return obj.ToString().Equals(ToString()); 
    } 

    public override int GetHashCode() 
    { 
     return ToString().GetHashCode(); 
    } 
} 

我:

private readonly IDictionary<StatisticsFilter, Statistics> _filteredStatisticsDict = 
      new Dictionary<StatisticsFilter, Statistics>(); 

.... 

{ 
    // ALWAYS EVALUATES TO FALSE! 
    if (_filteredStatisticsDict.ContainsKey(statisticsFilter) == false) 
    { 
     _filteredStatisticsDict.Add(statisticsFilter, new Statistics()); 
    } 
} 
+4

問題肯定在於你的'GetHashCode'。它是否總是爲相同的實例返回相同的值? – 2011-05-25 19:07:45

+0

你是否通過了課程的關鍵或實例? – MBen 2011-05-25 19:15:37

+0

等待,'ContainsKey(statisticsFilter)'評估爲false,或'ContainsKey(statisticsFilter)== false'評估爲false? – 2011-05-25 19:20:04

回答

5

無法重現與你給我們的代碼。

using System; 
using System.Collections.Generic; 

public class StatisticsFilter 
{ 
    private String someString1; 
    private String someString2; 

    public StatisticsFilter(string x, string y) 
    { 
     this.someString1 = x; 
     this.someString2 = y; 
    } 

    public override string ToString() 
    { 
     return string.Format("{0}-{1}xyz", someString1, someString2); 
    } 

    public override bool Equals(object obj) 
    {    
     return obj.ToString().Equals(ToString()); 
    } 

    public override int GetHashCode() 
    { 
     return ToString().GetHashCode(); 
    } 
} 

class Test 
{ 
    static void Main() 
    { 
     var dict = new Dictionary<StatisticsFilter, int>(); 

     var sf1 = new StatisticsFilter("hello", "there"); 
     var sf2 = new StatisticsFilter("hello", "there"); 

     dict[sf1] = 10; 
     Console.WriteLine(dict.ContainsKey(sf2)); // Prints true 
    } 
} 
+0

+1。問題在別處。 – Dmitry 2011-05-25 19:18:50

+0

你是對的。問題是統計過濾器實際上是同一個對象,並且與更新引用等有關。在我們的代碼中非常複雜和混亂。謝謝! – 2011-05-25 19:25:46

+0

'@jon Skeet看到類似的問題,我在這裏http://stackoverflow.com/questions/27921694/how-to-implement-comparison-on-a-class-that-c​​an-take-any-generic-type,請幫忙。謝謝。 – 2015-01-13 14:54:41

0

是否期待'ToString()'成爲關鍵?我想你一定會通過改變字典聲明得到期望的結果:Dictionary<string, Statistics>

// not always be false 
if (_filteredStatisticsDict.ContainsKey(statistics.ToString() == false) 
{ 
    _filteredStatisticsDict.Add(statisticsFilter.ToString(), newStatisitcs()); 
} 

如果我理解你正在試圖完成的任務,這應該工作。 使用此方法,字典關鍵字基於過濾器的內容。

+0

是的,這將工作,但它不是什麼字典實際上是如此不可讀。 – 2011-05-25 22:25:45