简体   繁体   English

IEqualityComparer + GroupB的GetHashCode中的断点未命中

[英]Breakpoint in GetHashCode of IEqualityComparer + GroupBy not hit

Code example: 代码示例:

 var positions = new List<Position>();

 for (int i = 0; i < 20; i++)
 {
     positions.Add(new Position { Code = "A", Value = i });
     positions.Add(new Position { Code = "A", Value = i });
 }
 var test = positions.GroupBy(p => p, new PositionComparer());

public class Position
{
    public string Code;
    public int Value;
}
public class PositionComparer : IEqualityComparer<Position>
{
    public bool Equals(Position x, Position y)
    {
        return x.Code == y.Code && x.Value == y.Value;
    }
    public int GetHashCode(Position pos)
    {
        unchecked
        {
           int hash = 17;
           hash = hash * 31 + pos.Code.GetHashCode();
           hash = hash * 31 + pos.Value;
           return hash;
         }
     }
 }

I have a breakpoint in GetHashCode (and in Equals ). 我在GetHashCode (和Equals )中有一个断点。
The breakpoint is not hit during the GroupBy , why not? GroupBy期间未命中断点,为什么不呢?

From the documentation for GroupBy : GroupBy文档中

This method is implemented by using deferred execution. 通过使用延迟执行来实现此方法。 The immediate return value is an object that stores all the information that is required to perform the action. 立即返回值是一个对象,该对象存储执行操作所需的所有信息。 The query represented by this method is not executed until the object is enumerated either by calling its GetEnumerator method directly or by using foreach in Visual C# or For Each in Visual Basic. 直到通过直接调用对象的GetEnumerator方法或在Visual C#中使用foreach或在Visual Basic中使用For Each枚举该对象,才会执行此方法表示的查询。

Unless you actually do something with test in your code the grouping won't actually be executed and therefore your PositionComparer won't get executed either. 除非您实际上在代码中对test进行了某些操作,否则实际上不会执行分组操作,因此也不会执行PositionComparer

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM