C# 如何比较两个字节数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12342714/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to compare two arrays of bytes
提问by Michael
I have two byte arrays with the exact same content. I tried:
我有两个内容完全相同的字节数组。我试过:
if (bytearray1 == bytearray2) {...} else {...}
and
和
if (Array.Equals(bytearray1, bytearray2)) {....} else {...}
All time it goes to the else! I don't know why! I checked both arrays manually several times!!!
所有的时间都去别的!我不知道为什么!我手动检查了两个阵列几次!!!
采纳答案by Darin Dimitrov
Try using the SequenceEqualextension method. For example:
尝试使用SequenceEqual扩展方法。例如:
byte[] a1 = new byte[] { 1, 2, 3 };
byte[] a2 = new byte[] { 1, 2, 3 };
bool areEqual = a1.SequenceEqual(a2); // true
回答by Justin Niessner
Both the ==operator and the Equals method will test reference equality. Since you have two separate arrays, they will never be equal.
无论是==操作者和equals方法将测试基准相等。由于您有两个单独的数组,因此它们永远不会相等。
Since you want to test that both arrays have the same content in the same order, try using the SequenceEqualmethod instead.
由于您想测试两个数组是否以相同的顺序具有相同的内容,请尝试使用该SequenceEqual方法。
回答by SLaks
The ==operator compares by reference; those are two different instances.
的==操作者比较由参考; 这是两个不同的例子。
Array.Equalsis really Object.Equals, which calls the instances Equalsmethod.
Since arrays do not override Equals(), this too compares by reference.
Array.Equalsis real Object.Equals,它调用实例Equals方法。
由于数组不覆盖Equals(),这也按引用进行比较。
Instead, you should call the LINQ SequenceEqual()method.
相反,您应该调用 LINQSequenceEqual()方法。

