問題描述
我已經(jīng)為 EventLogEntry 實現(xiàn)了一個自定義的 IEqualityComparer.
I've implemented a custom IEqualityComparer for EventLogEntry.
public class EventLogEntryListComparison :
IEqualityComparer<List<EventLogEntry>>,
IEqualityComparer<EventLogEntry>
對于IEqualityComparer
,GetHashCode函數(shù)很簡單.>
For IEqualityComparer<List<EventLogEntry>>
, the GetHashCode function is very simple.
public int GetHashCode(List<EventLogEntry> obj)
{
return obj.Sum(entry => 23 * GetHashCode(entry));
}
但是,對于某些條目,這會引發(fā) OverflowException.
However, this throws an OverflowException for certain entries.
"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.EventLogAnalysisEventLogEntryListComparison.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.EventLogAnalysisProgram.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()
在調試時嘗試得到相同的錯誤并且無法在即時窗口中出現(xiàn)后,我將代碼更改為這個并再見 OverflowException?
After trying to get the same error whilst debugging and couldn't in the immediate window, I changed the code to this and bye bye OverflowException?
int total = 0;
foreach (var eventLogEntry in obj)
{
total += GetHashCode(eventLogEntry);
}
return total;
LINQ 的 Sum 函數(shù)有何不同?
How is it that LINQ's Sum function behaving differently?
編輯 2
感謝一些評論,更正和預期的 GetHashCode 函數(shù)現(xiàn)在如下,
Thanks to a few comments, the corrected and intended GetHashCode function is now as follows,
public int GetHashCode(List<EventLogEntry> obj)
{
return unchecked(obj.Aggregate(17,
(accumulate, entry) =>
accumulate * 23 + GetHashCode(entry)));
}
推薦答案
LINQ 的 Enumerable.Sum(...)
方法在 checked
塊內執(zhí)行加法.這意味著如果總和溢出,他們會故意拋出異常.
LINQ's Enumerable.Sum(...)
methods perform the additions inside a checked
block. This means that they deliberately throw an exception if the sum overflows.
您的 sum 不在 checked
塊內,因此它是否引發(fā)異常取決于...是從 checked
塊內調用它,還是我相信在程序集上的一個屬性.
Your sum is not inside a checked
block, so whether or not it throws an exception depends on... whether it is called from inside a checked
block, or a property on the assembly I believe.
這篇關于LINQ 和溢出異常?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!