LINQ Sum OverflowException?

后端 未结 3 1031
广开言路
广开言路 2021-01-12 07:22

I\'ve implemented a custom IEqualityComparer for EventLogEntry.

public class EventLogEntryListComparison :
    IEqualityComparer         


        
相关标签:
3条回答
  • 2021-01-12 08:03

    It's because of the different behavior of Assemblies compiled in C# and the implementation of Enumerable.Sum.

    If you compile an Assembly in C#, by default all additions are performed in unchecked mode, which is why you don't get an overflow in your last example. If you want the runtime to throw on overflows, you need to use checked blocks (of course for your hash, you don't want that, so C#'s default behavior is fine).

    By contrast, Enumerable.Sum is meant to calculate a sum, and usually, you don't want sums to overflow. That's why Enumerable.Sum performs its calculations in checked mode, which throws an exception if the sum overflows.

    0 讨论(0)
  • 2021-01-12 08:05

    if you're computing a Hash Code, you may not want to use Sum anyways. Using Xor (^) will provide the same results and may even spread your hash codes out more than a sum will. Try this method:

    public int GetHashCode(List<EventLogEntry> obj)
    {
        int total = 0;
        foreach (var eventLogEntry in obj)
        {
            total ^= GetHashCode(eventLogEntry);
        }
    
        return total;
    }
    
    0 讨论(0)
  • 2021-01-12 08:08

    LINQ's Enumerable.Sum(...) methods perform the additions inside a checked block. This means that they deliberately throw an exception if the sum overflows.

    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.

    0 讨论(0)
提交回复
热议问题