我是否忘记了显而易见的,或者“手动”比较器是最好的方法吗?
基本上,我只想比较类型(小)字节数组的内容。如果所有字节都匹配,则结果应为true,否则为false。
我希望找到Array.Equals
或Buffer.Equals
会有所帮助。
演示代码:
var a = new byte[]{1, 2, 3, 4, 5};
var b = new byte[]{1, 2, 3, 4, 5};
Console.WriteLine(string.Format("== : {0}", (a == b)));
Console.WriteLine(string.Format("Equals : {0}", a.Equals(b)));
Console.WriteLine(string.Format("Buffer.Equals : {0}", Buffer.Equals(a, b)));
Console.WriteLine(string.Format("Array.Equals = {0}", Array.Equals(a, b)));
Console.WriteLine(string.Format("Manual_ArrayComparer = {0}", ArrayContentsEquals(a, b)));
手动功能:
/// <summary>Returns true if all elements of both byte-arrays are identical</summary>
public static bool ArrayContentsEquals(byte[] a, byte[] b, int length_to_compare = int.MaxValue)
{
if (a == null || b == null) return false;
if (Math.Min(a.Length, length_to_compare) != Math.Min(b.Length, length_to_compare)) return false;
length_to_compare = Math.Min(a.Length, length_to_compare);
for (int i = 0; i < length_to_compare; i++) if (a[i] != b[i]) return false;
return true;
}