有什么问题确实IStructuralEquatable和IStructuralComparable解决? [英] What problem does IStructuralEquatable and IStructuralComparable solve?

查看:266
本文介绍了有什么问题确实IStructuralEquatable和IStructuralComparable解决?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经注意到了这两个接口,和一些相关的课程,已在.NET 4中添加他们似乎有点画蛇添足我;我读过关于他们的多个博客,但我仍然无法找出问题,他们解决的是.NET 4以前棘手。

I've noticed these two interfaces, and several associated classes, have been added in .NET 4. They seem a bit superfluous to me; I've read several blogs about them, but I still can't figure out what problem they solve that was tricky before .NET 4.

有什么用 IStructuralEquatable IStructuralComparable

推荐答案

所有类型的.NET支持的的Object.Equals()方法,默认情况下,比较两个类型的引用相等。但是,有时,它是也希望能够比较两个类型的结构相等

All types in .NET support the Object.Equals() method which, by default, compares two types for reference equality. However, sometimes, it also desirable to be able to compare two types for structural equality.

这方面最好的例子就是阵列,它与.NET 4现在执行 IStructuralEquatable 接口。这使得可以区分是否正在比较两个阵列引用相等,或为结构相等 - 它们是否有与在每个位置相同的值相同的项目数。这里有一个例子:

The best example of this is arrays, which with .NET 4 now implement the IStructuralEquatable interface. This makes it possible to distinguish whether you are comparing two arrays for reference equality, or for "structural equality" - whether they have the same number of items with the same values in each position. Here's an example:

int[] array1 = new int[] { 1, 5, 9 };
int[] array2 = new int[] { 1, 5, 9 };

// using reference comparison...
Console.WriteLine( array1.Equals( array2 ) ); // outputs false

// now using the System.Array implementation of IStructuralEquatable
Console.WriteLine( StructuralComparisons.StructuralEqualityComparer.Equals( array1, array2 ) ); // outputs true

其中实现结构相等/可比性的其它类型包括元组和匿名类型 - 其中两个明显受益执行基于它们的结构和内容的比较的能力。

Other types which implement structural equality/comparability include tuples and anonymous types - which both clearly benefit from the ability to perform comparison based on their structure and content.

你没问的一个问题是:

为什么我们 IStructuralComparable IStructuralEquatable 时,有已经   存在 IComparable的 IEquatable 接口?

Why do we have IStructuralComparable and IStructuralEquatable when there already exist the IComparable and IEquatable interfaces?

我将提供答案是,在一般情况下,这是理想的参考比较和结构的比较来区分。它通常预计,如果实现 IEquatable< T> .Equals 你也将覆盖的Object.Equals 是一致的。在这种情况下,你将如何支持参考和结构相等?

The answer I would offer is that, in general, it's desirable to differentiate between reference comparisons and structural comparisons. It's normally expected that if you implement IEquatable<T>.Equals you will also override Object.Equals to be consistent. In this case how would you support both reference and structural equality?

这篇关于有什么问题确实IStructuralEquatable和IStructuralComparable解决?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆