我正在使用ConcurrentDictionary,关键是由具有公共属性的类组成。
在使用来自(HashCode on decimal with IEqualityComparer in a ConcurrentDictionary)的代码后,我想找到一个解决方案,所以我不必为我制作的每个属性类实现具有接口IEqualityComparer的类。
我已经创建了一个基类,可以检查是否设置了所有公共属性(或者至少不是默认值)。所以,我想,试一试,将IEqualityComparer类添加到基类。
到目前为止,我有这个,它确实有效。using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
private void SomeMethod()
{
ConcurrentDictionary<TwoUintsOneStringsKeyInfo,int> test = new ConcurrentDictionary<TwoUintsOneStringsKeyInfo, int>(new TwoUintsOneStringsKeyInfo.EqualityComparerElevenUintsKeyInfo());
test.TryAdd(new TwoUintsOneStringsKeyInfo { IdOne = 1, IdTwo = 2, mySTring = "Hi" }, 1);
test.TryAdd(new TwoUintsOneStringsKeyInfo { IdOne = 2, IdTwo = 3, mySTring = "hello" }, 2);
test.TryAdd(new TwoUintsOneStringsKeyInfo { IdOne = 3, IdTwo = 4 }, 3);
int result;
test.TryGetValue(new TwoUintsOneStringsKeyInfo { IdOne = 2, IdTwo = 3, mySTring = "hello" }, out result);
}
public class PropertyBaseClass
{
public bool AllPublicProperiesAreSet()
{
//some logic (removed for now. Not important for the question)
}
public class EqualityComparerElevenUintsKeyInfo : IEqualityComparer<TwoUintsOneStringsKeyInfo>
{
public int GetHashCode(TwoUintsOneStringsKeyInfo obj)
{
int hash = 17;
System.Reflection.PropertyInfo[] properties = obj.GetType().GetProperties().OrderBy(x=>x.Name).ToArray();
int counter=0;
foreach(System.Reflection.PropertyInfo p in properties)
{
counter++;
var value = p.GetValue(obj);
hash = hash * 23 + (value == null ? (Math.Pow(1.111, counter)).GetHashCode() : value.GetHashCode());
}
return hash;
}
public bool Equals(TwoUintsOneStringsKeyInfo x, TwoUintsOneStringsKeyInfo y)
{
return x.IdOne == y.IdOne &&
x.IdTwo == y.IdTwo;
}
}
}
public class TwoUintsOneStringsKeyInfo : PropertyBaseClass
{
public uint IdOne { get; set; }
public uint IdTwo { get; set; }
public string mySTring { get; set; }
}
我用三个属性制作了这个例子。通常有更多和更多不同的类型,我只是不想在concurrentDictionary中为每个属性类创建一个自定义类。
事情(当然),它现在的方式,它只适用于类型为TwoUintsOneStringsKeyInfo的属性类,因为我必须在实现IEqualityComparer&lt;&gt;时指定它。
有没有什么方法可以将EqualityComparerElevenUintsKeyInfo类实现到基类,并使其灵活,使EqualityComparerElevenUintsKeyInfo检查哪个类实现EqualityComparerElevenUintsKeyInfo,并将该类用作IEqualityComparer,GetHashCode和Equals的参数(如果可以的话)为了做我想做的事,我当然也会改变Equals方法。
建议?
亲切的问候,
Matthijs