我正在检查两个字节数组的相等性,我想要一些帮助,因为即使数组应该相等,我也会返回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;
}
Run Code Online (Sandbox Code Playgroud)
这总是返回false : (a1[i]==b1[i]).
p.s*_*w.g 42
您需要在某处添加返回值.这应该工作:
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;
}
Run Code Online (Sandbox Code Playgroud)
但这更简单:
return a1.SequenceEqual(b1);
Run Code Online (Sandbox Code Playgroud)
或者,您可以使用IStructuralEquatable.NET 4:
return ((IStructuralEquatable)a1).Equals(b1, StructuralComparisons.StructuralEqualityComparer)
Run Code Online (Sandbox Code Playgroud)
Mag*_*nus 38
要检查相等性,您可以写:
var areEqual = a1.SequenceEqual(b1);
Run Code Online (Sandbox Code Playgroud)
我建议您进行一些短路处理,以使事情更简单一些;object.ReferenceEquals如果数组是相同的引用(a1 = b1),请使用进行短路处理:
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;
}
Run Code Online (Sandbox Code Playgroud)