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

Mas*_*yah 25 c#

我正在检查两个字节数组的相等性,我想要一些帮助,因为即使数组应该相等,我也会返回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)

  • 但如果它确实与他的框架相匹配,那么这是一种更好的方法. (8认同)
  • @MikePrecup在这一天是一个时代,***除非明确指定***,我认为可以安全地假设正在进行的任何项目都是3.5+.[67%的.NET用户使用版本4,26%使用某些版本的3](http://web.archive.org/web/20120919192827/http://statowl.com/microsoft_dotnet.php). (3认同)
  • 从技术上讲,LINQ可能与他的框架不匹配 (2认同)
  • @Moop Linq 已经存在 6 年了,当然大多数人现在至少已经升级到框架 3.5。 (2认同)

Han*_*ney 5

我建议您进行一些短路处理,以使事情更简单一些;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)