在.NET GetHashCode方法中,很多地方都使用.NET 方法.特别是在快速查找集合中的项目或确定相等性时.是否有关于如何GetHashCode为我的自定义类实现覆盖的标准算法/最佳实践,因此我不会降低性能?
我为EventLogEntry实现了一个自定义的IEqualityComparer.
public class EventLogEntryListComparison :
IEqualityComparer<List<EventLogEntry>>,
IEqualityComparer<EventLogEntry>
Run Code Online (Sandbox Code Playgroud)
对于IEqualityComparer<List<EventLogEntry>>,GetHashCode函数非常简单.
public int GetHashCode(List<EventLogEntry> obj)
{
return obj.Sum(entry => 23 * GetHashCode(entry));
}
Run Code Online (Sandbox Code Playgroud)
但是,这会为某些条目抛出OverflowException.
"Arithmetic operation resulted in an overflow."
at System.Linq.Enumerable.Sum(IEnumerable`1 source)
at System.Linq.Enumerable.Sum[TSource](IEnumerable`1 source, Func`2 selector)
at <snip>.Diagnostics.EventLogAnalysis.EventLogEntryListComparison.GetHashCode(List`1 obj) in C:\dev\<snip>Diagnostics.EventLogAnalysis\EventLogEntryListComparison.cs:line 112
at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
at System.Collections.Generic.Dictionary`2.set_Item(TKey key, TValue value)
at <snip>.Diagnostics.EventLogAnalysis.Program.AnalyseMachine(String validMachineName) in C:\dev\<snip>.Diagnostics.EventLogAnalysis\Program.cs:line 104
at System.Threading.Tasks.Parallel.<>c__DisplayClass2d`2.<ForEachWorker>b__23(Int32 i)
at System.Threading.Tasks.Parallel.<>c__DisplayClassf`1.<ForWorker>b__c()
Run Code Online (Sandbox Code Playgroud)
在调试时尝试获得相同的错误并且无法在即时窗口中,我将代码更改为此并再见了OverflowException?
int total = 0;
foreach (var eventLogEntry in obj)
{
total += GetHashCode(eventLogEntry); …Run Code Online (Sandbox Code Playgroud) 我有以下课程
public class ModInfo : IEquatable<ModInfo>
{
public int ID { get; set; }
public string MD5 { get; set; }
public bool Equals(ModInfo other)
{
return other.MD5.Equals(MD5);
}
public override int GetHashCode()
{
return MD5.GetHashCode();
}
}
Run Code Online (Sandbox Code Playgroud)
我使用如下方法将一些数据加载到该类的列表中:
public void ReloadEverything() {
var beforeSort = new List<ModInfo>();
// Bunch of loading from local sqlite database.
// not included since it's reload boring to look at
var modinfo = beforeSort.OrderBy(m => m.ID).AsEnumerable().Distinct().ToList();
}
Run Code Online (Sandbox Code Playgroud)
问题是Distinct()呼叫似乎没有做到这一点.仍然存在彼此相等的对象.
根据这篇文章:https://msdn.microsoft.com/en-us/library/vstudio/bb348436%28v=vs.100%29.aspx这 是你应该如何做出不同的工作,但它不似乎是在ModInfo对象上调用Equals方法.是什么导致这种情况发生? …