代码示例:
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;
}
}
}
我在 GetHashCode
(和 Equals
)中有一个断点。
在 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.
除非您实际在代码中使用 test
执行某些操作,否则实际上不会执行分组,因此您的 PositionComparer
也不会执行。
关于c# - 未命中 IEqualityComparer + GroupBy 的 GetHashCode 中的断点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44001698/