且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

T&GT ;,的IEqualityComparer< IEquatable℃之间的差异T>和压倒一切的.Equals()上的自定义对象集合使用LINQ是什么时候?

更新时间:2023-01-23 17:24:13

这不要紧,你是否覆盖的Object.Equals 对象。 GetHash code ,实施 IEquatable ,或提供的IEqualityComparer 。所有这些的可以的工作,只是方式略有不同。

It doesn't matter whether you override object.Equals and object.GetHashCode, implement IEquatable, or provide an IEqualityComparer. All of them can work, just in slightly different ways.

1)重写等于 GetHash code 对象

这是基本的情况下,在感。它通常会工作,假设你在编辑的类型,以确保作为期望这两种方法的执行位置是。有没有错,在许多情况下只是这做的。

This is the base case, in a sense. It will generally work, assuming you're in a position to edit the type to ensure that the implementation of the two methods are as desired. There's nothing wrong with doing just this in many cases.

2)实施 IEquatable

这里的关键是,你可以(也应该)落实 IEquatable< YourTypeHere> 。这和#1之间的主要区别是,你必须为等于法强类型,而不是仅仅有它使用对象。这是既为方便程序员(增加类型安全)更好,也意味着任何值类型将不被加框,所以这可以提高自定义结构的性能。如果你这样做,你应该pretty多少总是做它的除#1,的而不是替代。具有等于此处方法在功能上不同于的Object.Equals 将是...坏。不这样做。

The key point here is that you can (and should) implement IEquatable<YourTypeHere>. The key difference between this and #1 is that you have strong typing for the Equals method, rather than just having it use object. This is both better for convenience to the programmer (added type safety) and also means that any value types won't be boxed, so this can improve performance for custom structs. If you do this you should pretty much always do it in addition to #1, not instead of. Having the Equals method here differ in functionality from object.Equals would be...bad. Don't do that.

3)实施的IEqualityComparer

这是从第一两个完全不同的。这里的想法是,对象是没有得到它自己的哈希值code,或者看它是否等于别的东西。这种方法的一点是,的对象不知道如何正确地得到它的hash或者看它是否等于别的的。也许是因为你不控制的类型(即第三方库)的code和他们没有打扰重写的行为,或者他们没有覆盖它,但你只是想自己独特的定义平等在此特定上下文。

This is entirely different from the first two. The idea here is that the object isn't getting it's own hash code, or seeing if it's equal to something else. The point of this approach is that an object doesn't know how to properly get it's hash or see if it's equal to something else. Perhaps it's because you don't control the code of the type (i.e. a 3rd party library) and they didn't bother to override the behavior, or perhaps they did override it but you just want your own unique definition of "equality" in this particular context.

在这种情况下,建立一个完全独立的比较器对象,它发生在两个不同的对象并通知您它们是否相等或没有,或什么人对象的哈希code是。当使用这种解决方案的也无所谓什么等于 GetHash code 方法做该类型本身的,你不会使用它。

In this case you create an entirely separate "comparer" object that takes in two different objects and informs you of whether they are equal or not, or what the hash code of one object is. When using this solution it doesn't matter what the Equals or GetHashCode methods do in the type itself, you won't use it.

请注意,所有这一切是从 == 运营商,这是它自己的野兽完全无关。

Note that all of this is entirely unrelated from the == operator, which is its own beast.