gpt4 book ai didi

c# - 在字典中创建匿名类作为自定义键

转载 作者:太空狗 更新时间:2023-10-29 17:38:37 25 4
gpt4 key购买 nike

在使用字典时,我总是重写 GetHashCode 和 Equals(或为字典提供自定义比较器)。

当我创建一个匿名类作为键时,幕后发生了什么?

示例代码....

 var groups=(from item in items
group item by new { item.ClientId, item.CustodianId, item.CurrencyId }
into g
select new {
Key=g.Key,
Sum=g.Sum(x => x.Cash)
}).ToDictionary(item=>item.Key,item=>item.Sum);

这段代码给了我预期的结果,但我没有为匿名类提供 GetHashCode 和 Equals 方法。这段代码不应该无法根据匿名类中的项目对我的项目进行分组吗??

最佳答案

不会 - 匿名类会自动生成适当的 Equals/GetHashCode 实现。

来自 C# 语言规范,第 7.5.10.6 节:

The Equals and GetHashcode methods on anonymous types override the methods inherited from object, and are defined in terms of the Equals and GetHashcode of the properties, so that two instances of the same anonymous type are equal if and only if all their properties are equal.

关于c# - 在字典中创建匿名类作为自定义键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2161041/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com