0

今天我用 ConcurrentDictionary 和 Dictionary 做了一些测试:

class MyTest
{
    public int Row { get; private set; }
    public int Col { get; private set; }
    public string Value { get; private set; }

    public MyTest(int row, int col, string value)
    {
        this.Col = col;
        this.Row = row;
        this.Value = value;
    }


    public override bool Equals(object obj)
    {
        MyTest other = obj as MyTest;
        return base.Equals(other);

    }

    public override int GetHashCode()
    {
        return (Col.GetHashCode() ^ Row.GetHashCode() ^ Value.GetHashCode());
    }

}

使用上面的实体,我创建并填充了 ConcurrentDictionary 和 Dictionary 并尝试了以下代码:

    ConcurrentDictionary<MyTest, List<MyTest>> _test = new ConcurrentDictionary<MyTest, List<MyTest>>();
    Dictionary<MyTest, List<MyTest>> _test2 = new Dictionary<MyTest, List<MyTest>>();

        MyTest dunno = _test.Values.AsParallel().Select(x => x.Find(a => a.Col == 1 && a.Row == 1)).FirstOrDefault();
        MyTest dunno2 = _test2.Values.AsParallel().Select(x => x.Find(a => a.Col == 1 && a.Row == 1)).FirstOrDefault();

第一个返回值,但第二个没有,我做错了什么?

这是用于添加值的代码:

            _test.AddOrUpdate(cell10,
            new List<MyTest>
            {
                new MyTest(1, 1, "ovpSOMEVALUEValue"),
                new MyTest(1, 2, "ocpSOMEVALUEValue")
            },
            (key, value) => value = new List<MyTest>());

        _test2.Add(cell10,
            new List<MyTest>
            {
                new MyTest(1, 1, "ovpSOMEVALUEValue"),
                new MyTest(1, 2, "ocpSOMEVALUEValue")
            }
            );
4

1 回答 1

3

您正在调用AddOrUpdate,并且您的第三个参数是它应该创建一个新的空列表,因此结果是您最终得到一个空列表。我猜想在这行代码之前的某个地方,您正在添加一个具有相同键的条目。

还要注意Equals函数不正确。您正在比较参考,而不是您在GetHashCode. 我建议您使用默认模板来覆盖 Equals:

     protected bool Equals(x other) {
        return Row == other.Row && Col == other.Col && string.Equals(Value, other.Value);
     }

     public override bool Equals(object obj)
     {
        if (ReferenceEquals(null, obj)) return false;
        if (ReferenceEquals(this, obj)) return true;
        if (obj.GetType() != this.GetType()) return false;
        return Equals((x) obj);
     }

     public override int GetHashCode()
     {
        unchecked
        {
           var hashCode = Row;
           hashCode = (hashCode*397) ^ Col;
           hashCode = (hashCode*397) ^ (Value != null ? Value.GetHashCode() : 0);
           return hashCode;
        }
     }
于 2016-10-07T03:22:05.077 回答