gpt4 book ai didi

c# - 更喜欢 EqualityComparer 而不是 IEqualityComparer

转载 作者:IT王子 更新时间:2023-10-29 04:02:43 25 4
gpt4 key购买 nike

摘自MSDN上 IEqualityComparer<T> 备注部分:

  1. We recommend that you derive from the EqualityComparer<T> class instead of implementing the IEqualityComparer<T> interface, because the EqualityComparer<T> class tests for equality using the IEquatable<T>.Equals method instead of the Object.Equals method. ...

    • 我不理解引用中关于我们为什么更愿意从 EqualityComparer<T> 类派生而不是实现 IEqualityComparer<T> 的论点。这意味着实现 IEqualityComparer<T> 的对象将使用 Object.Equals 测试相等性,但是当我们不想使用 IEqualityComparer<T>Object.Equals 测试相等性时,实现 IEquatable<T>.Equals 不是全部意义所在吗?

    • 这也意味着如果我们从 EqualityComparer<T> 派生,那么派生类将使用 IEquatable<T>.Equals 方法测试是否相等。同样,当我们不想使用 EqualityComparer<T>Object.Equals 测试相等性时(因为 IEquatable<T>.Equals 已经使用 EqualityComparer<T>.DefaultObject.Equals 进行测试),从 IEquatable<T>.Equals 派生的全部意义不是吗?

  2. ... This is consistent with the Contains, IndexOf, LastIndexOf, and Remove methods of the Dictionary<TKey, TValue> class and other generic collections.

    • 我假设 .NET 库中的大多数集合通过调用 IEqualityComparer<T>IEquatable<T>.Equals 测试元素的默认相等性(即当用户不向这些集合提供他们自己的自定义 Object.Equals 对象时) (取决于类型 T 的元素是否实现 IEquatable<T> )通过 EqualityComparer<T>.Default

    • 为什么这些集合(在测试默认相等性时)不直接调用 IEquatable<T>.EqualsObject.Equals 而不是通过 EqualityComparer<T>.Default 类?

最佳答案

关于您的第一个问题:

备注部分为 IEqualityComparer<T> class 似乎并没有真正提供为什么您应该更喜欢从抽象类派生而不是接口(interface)的原因,这听起来更像是平等比较器接口(interface)首先存在的原因。它所说的实际上是无用的,它基本上描述了默认实现正在做什么。如果有的话,他们在这里提供的“推理”听起来更像是你的比较者可以做什么的指南,而与它实际做什么无关。

查看 EqualityComparer<T> 的公共(public)/ protected 接口(interface)类,只有一个可取之处,它实现了非泛型 IEqualityComparer界面。我认为他们的意思是说他们建议从中派生,因为 EqualityComparer<T>实际上实现了非泛型 IEqualityComparer接口(interface),这样你的类就可以在需要非通用比较器的地方使用。

IComparer<T> 的备注部分确实更有意义:

We recommend that you derive from the Comparer<T> class instead of implementing the IComparer<T> interface, because the Comparer<T> class provides an explicit interface implementation of the IComparer.Compare method and the Default property that gets the default comparer for the object.

我怀疑它应该为 IEqualityComparer<T> 说类似的话但有些想法被混淆了,最终导致描述不完整。


关于你的第二个问题:

图书馆馆藏的主要目标是尽可能灵活。一种方法是允许通过提供 IComparer<T> 来比较对象中的自定义方法。或 IEqualityComparer<T>做比较。在没有提供默认比较器的情况下获取默认比较器的实例比直接进行比较要容易得多。这些比较器反过来可以包含调用适当打包的适当比较所需的逻辑。

例如,默认比较器可以确定是否T工具 IEquatable<T>并调用IEquatable<T>.Equals在物体上或以其他方式使用 Object.Equals .最好封装在比较器中,而不是可能在集合代码中重复。

此外,如果他们想退回到调用 IEquatable<T>.Equals直接地,他们必须在 T 上添加约束这将使这个电话成为可能。这样做会降低灵 active ,并抵消了首先提供比较器的好处。

关于c# - 更喜欢 EqualityComparer<T> 而不是 IEqualityComparer<T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5707347/

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