C# 字典包含Key
我的问题是 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());
}
}
My problem is ContainsKey is always returning false even when they key has been added and .Equals evaluates to true.
I have the following class:
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();
}
}
I then have a dictionary that looks like this:
private readonly IDictionary<StatisticsFilter, Statistics> _filteredStatisticsDict =
new Dictionary<StatisticsFilter, Statistics>();
....
{
// ALWAYS EVALUATES TO FALSE!
if (_filteredStatisticsDict.ContainsKey(statisticsFilter) == false)
{
_filteredStatisticsDict.Add(statisticsFilter, new Statistics());
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
无法使用您提供给我们的代码进行重现。
Unable to reproduce with the code you've given us.
是否期望“ToString()”成为关键?我认为通过将 Dictionary 声明更改为:
Dictionary
如果我理解您要实现的目标,那么您将获得所需的结果,这应该可行。
使用此方法,字典键基于过滤器的内容。
Are expecting the 'ToString()' to be the key? I think you will get the desired result by changing the Dictionary declaration to:
Dictionary<string, Statistics>
If I understand what you are trying to accomplish, this should work.
With this method the dictionary key is based on the content of the filter.