可.NET测试阵列等效,而不仅仅是平等的参考? [英] Can .NET test arrays for equivalence and not just equal references?

查看:130
本文介绍了可.NET测试阵列等效,而不仅仅是平等的参考?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var a = new double[] {1, 2, 3};
var b = new double[] {1, 2, 3};
System.Console.WriteLine(Equals(a, b)); // Returns false

不过,我正在寻找一种方法来比较数组这将比较refernces的内部值来代替。是否有一个内置的方式做到这一点。NET中?

However, I'm looking for a way to compare arrays which would compare the internal values instead of refernces. Is there a built in way to do this in .NET?

此外,虽然我理解等于比较基准, GetHash code 对于这两个数组返回的值不同同时,我觉得是不应该的,因为它们具有相同的内部价值。

Also, while I understand Equals comparing references, GetHashCode returns different values for these two arrays also, which I feel shouldn't happen, since they have the same internal values.

推荐答案

我相信你正在寻找的 Enumerable.SequenceEqual< TSource>(IEnumerable的< TSource>中的IEnumerable< TSource>) 方法

I believe you are looking for the Enumerable.SequenceEqual<TSource>(IEnumerable<TSource>, IEnumerable<TSource>) method.

var a = new double[] {1, 2, 3};
var b = new double[] {1, 2, 3};
System.Console.WriteLine(a.SequenceEqual(b)); // Returns true

至于问题GetHash code返回不同的值,请记住,你与两个不同的价值观在这里处理。 您没有比较数组,你比较两个引用数组。

对于引用类型的默认相等比较一致就可以了。如果你需要别的东西发生记得有一个对于使用 <$建造模型C $ C>的IEqualityComparer&LT; T&GT; ,它允许您根据不遵循标准的引用相等模式的具体需求来定义自定义相等比较

Default equality comparison for reference types needs to be consistent. If you need something else to happen remember there is a built in model for that using IEqualityComparer<T> which allows you to define custom equality comparison based on specific needs that don't follow the standard reference equality pattern.

这篇关于可.NET测试阵列等效,而不仅仅是平等的参考?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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