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

C#:GetHashCode、Equals和Dictionary导致IndexOutOfRangeException?,c#,.net,exception,dictionary,C#,.net,Exception,Dictionary,可能重复: 这个很时髦。我不能轻易地弄清事情的真相。在日志中发现异常并找出一些旧代码。不要问我为什么这样写,因为我不知道。问题实际上是在设置字典项时抛出IndexOutOfRangeException的条件是什么。下面是事情的样子: public MyEnum { Undefined = 0, B = 1, C = 2, D = 16, All = B | C | D } public class MC { private int _hashCode; private int _i

可能重复:

这个很时髦。我不能轻易地弄清事情的真相。在日志中发现异常并找出一些旧代码。不要问我为什么这样写,因为我不知道。问题实际上是在设置字典项时抛出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
}

如何使生产线失败?不要把注意力分散到错误的方向上,但我认为Equals和GetHashCode有些可疑,但到目前为止,我无法证明这一点——没有使用单元测试框架进行重新编程

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


请参阅:

这是抛出错误的多线程代码吗?您运行的框架版本是什么?@MitchWheat:问得好。是的。事实上,我忽略了一件重要的事情,即dictionary实际上是执行该赋值的worker类的静态成员。投票以dup的身份结束。
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)