2

我的问题是 ContainsKey 总是返回 false,即使它们已添加密钥并且 .Equals 评估为 true。

我有以下课程:

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

2 回答 2

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
    }
}
于 2011-05-25T19:15:05.743 回答
0

期望 'ToString()' 是关键吗?我认为您将通过将 Dictionary 声明更改为:Dictionary<string, Statistics>

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

如果我了解您要完成的工作,那应该可以。使用此方法,字典键基于过滤器的内容。

于 2011-05-25T19:21:15.063 回答