Can .NET test arrays for equivalence and not just equal references?

筅森魡賤 提交于 2020-01-13 09:44:08

问题


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

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?

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.


回答1:


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

As far as the issue with GetHashCode returning different values, remember that you are dealing with two distinct values here. You are not comparing arrays, you are comparing two references to arrays.

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.




回答2:


UPDATE: Fixed code to use the correct comparison method (thanks to @CodesInChaos for pointing that out).

If you're in .NET 4, you can use the IStructuralEquatable interface:

IStructuralEquatable c = b;
Console.WriteLine(c.Equals(a, StructuralComparisons.StructuralEqualityComparer));

This question has more detail.



来源:https://stackoverflow.com/questions/5813113/can-net-test-arrays-for-equivalence-and-not-just-equal-references

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!