C#:GetHashCode、Equals 和 Dictionary 导致 IndexOutOfRangeException?

标签 c# .net exception dictionary

Possible Duplicate:
When does a dictionary throw an IndexOutOfRangeException on Add or ContainsKey?

这个很时髦。我无法轻松地探究到底。在日志中发现异常,挖出了一些旧代码。不要问我为什么这样写,因为我不知道。问题实际上是在设置字典的 Item 时抛出 IndexOutOfRangeException 的条件是什么。事情是这样的:

public MyEnum { Undefined = 0, B = 1, C = 2, D = 16, All = B | C | D }

public class MC 
{
  private int _hashCode;
  private int _i;
  private MyEnum _e;

  public MC(int i, MyEnum e)
  {
     _i = i;
     _e = e;
     SetHashCode();
  }

  private SetHashCode()
  {
    _hashCode = _i * 31 + (int)e;
  }

  public override bool Equals(object other)
  {
    if (!(obj is MC))
    {
      return false;
    }
    MC other = (MC)obj;
    return ((_i == other._i) && (_e == other._e));
  }

  public override int GetHashCode()
  {
    return _hashCode;
  }
}

...

var d = new Dictionary<MC, DateTime>();
...
// Create and populate the list of MCs
var mcs = new List<MC>();
...
foreach (MC mc in mcs) 
{
  ...
  d[mc] = DateTime.UtcNow; // Pukes here
}

异常(exception)是:

System.IndexOutOfRangeException, Source: mscorlib    Index was outside the bounds of the array.       at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)

如何让线路失败?不要将你的注意力转移到错误的方向,但我认为 Equals 和 GetHashCode 有一些可疑的地方,但到目前为止我无法证明这一点 - 没有使用单元测试框架进行重现。

最佳答案

您遇到的错误通常是由对字典的多线程、未锁定的并发访问引起的。

参见:When does a dictionary throw an IndexOutOfRangeException on Add or ContainsKey?

关于C#:GetHashCode、Equals 和 Dictionary 导致 IndexOutOfRangeException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7720122/

相关文章:

xml - XPathException 无效 token

c# - 如何使用太长/重复的路径处理解压缩 ZipFile

c# - 配置串口

c# - .NET 正则表达式空白特殊字符

java - ActionListener 类中的哈希字符串 (SHA-256)

java - Eclipse 中通知未处理异常的配置是什么?

c# - 使用 Oledbconnection 时出现编译错误

c# - Image.FromFile() 或 FromStream() 在 GdiplusStartup 上挂起

c# - DbContext 损坏附加实体 : why?

c# - 错误 : Must create DependencySource on same Thread as the DependencyObject even by using Dispatcher