检查两个字节数组的相等性

我正在检查两个字节数组的相等性,我想要一些帮助,因为即使数组应该相等,我也会返回false。

在我的调试中,我可以看到a1和b1都相等,但它不会进入while循环内来增加i。

public bool Equality(byte[] a1, byte[] b1) { int i; bool bEqual; if (a1.Length == b1.Length) { i = 0; while ((i < a1.Length) && (a1[i]==b1[i])) { i++; } if (i == a1.Length) { bEqual = true; } } return bEqual; } 

这总是返回false: (a1[i]==b1[i])

您需要在某处添加返回值。 这应该工作:

 public bool Equality(byte[] a1, byte[] b1) { int i; if (a1.Length == b1.Length) { i = 0; while (i < a1.Length && (a1[i]==b1[i])) //Earlier it was a1[i]!=b1[i] { i++; } if (i == a1.Length) { return true; } } return false; } 

但这更简单:

 return a1.SequenceEqual(b1); 

或者,您可以使用.NET 4中的IStructuralEquatable

 return ((IStructuralEquatable)a1).Equals(b1, StructuralComparisons.StructuralEqualityComparer) 

要检查相等性,您可以写:

 var areEqual = a1.SequenceEqual(b1); 

我建议使用一些短路来使事情变得更简单,并且当数组是相同的引用( a1 = b1 )时,使用object.ReferenceEquals来短路:

 public bool Equality(byte[] a1, byte[] b1) { // If not same length, done if (a1.Length != b1.Length) { return false; } // If they are the same object, done if (object.ReferenceEquals(a1,b1)) { return true; } // Loop all values and compare for (int i = 0; i < a1.Length; i++) { if (a1[i] != b1[i]) { return false; } } // If we got here, equal return true; } 

这应该工作:

 public bool Equality(byte[] a1, byte[] b1) { if(a1 == null || b1 == null) return false; int length = a1.Length; if(b1.Length != length) return false; while(length >0) { length--; if(a1[length] != b1[length]) return false; } return true; } 

你应该添加一些return语句:

 public bool Equality(byte[] a1, byte[] b1) { int i = 0; if (a1.Length == b1.Length) { while ((i < a1.Length) && (a1[i]==b1[i])) { i++; } } return i == a1.Length; } 

或者,更好

 public bool Equality(byte[] a1, byte[] b1) { if(a1.Length != b1.Length) { return false; } for (int i = 0; i < a1.Length; i++) { if (a1[i] != b1[i]) { return false; } } return true; }