C# - 字节数组 - byte[] - 有简单的比较器吗?
C# - byte array - byte[] - Is there a simple comparer?
我是不是忘记了显而易见的东西,还是 "manual" 比较器是最好的选择?
基本上,我只想比较类型(小)字节数组的内容。如果所有字节都匹配,则结果应为真,否则为假。
我原以为 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;
}
您正在寻找 SequenceEqual
方法。
a.SequenceEqual(b);
Determines whether two sequences are equal by comparing the elements by using the default equality comparer for their type.
我是不是忘记了显而易见的东西,还是 "manual" 比较器是最好的选择?
基本上,我只想比较类型(小)字节数组的内容。如果所有字节都匹配,则结果应为真,否则为假。
我原以为 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;
}
您正在寻找 SequenceEqual
方法。
a.SequenceEqual(b);
Determines whether two sequences are equal by comparing the elements by using the default equality comparer for their type.