我想在2字节数组之间使用Extension方法"Equals"

Shi*_*mmy 1 c# binary comparison equality bytearray

我正在做一些byte []比较.

我试过==但这就像基本的Equals,它:

byte[] a = {1,2,3};
byte[] b = {1,2,3};
bool equals = a == b; //false
equals = a.Equals(b); //false
Run Code Online (Sandbox Code Playgroud)

我试图添加一个扩展方法,但由于重载的基类'Equals采用相同的参数,它转到基本方法而不是扩展,无论如何我可以使用Equals扩展(不要改变它的名字......)或(甚至更好)使用==运算符?

这是我实际要比较的内容:

public static bool ContentEquals(this byte[] array, byte[] bytes)
{
    if (array == null || bytes == null) throw new ArgumentNullException();
    if( array.Length != bytes.Length) return false;
    for (int i = 0; i < array.Length; i++)
        if (array[i] != bytes[i]) return false;

    return true;
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 7

您当然不能使用扩展方法进行运算符重载.它不适用于该Equals方法的原因是,如果在不使用扩展方法的情况下适用任何方法,则在甚至检查扩展方法之前将选择该方法.

即使你的Equals方法在将参数类型转换为形式参数类型方面"更好",编译器总是更喜欢"普通"方法.你必须给你的方法一个不同的名字.

但是,您始终可以使用该Enumerable.SequenceEquals方法.我不认为这会使长度检查发生短路(即使它可以ICollection<T>实现).您可以自己实现更高效的版本.实际上,如果你只是改变现有的数组实现来调用SequenceEquals甚至ArrayEquals,那就没问题了:

public static bool ArrayEquals(this byte[] array, byte[] bytes)
{
    // I'd personally use braces in all of this, but it's your call
    if (array.Length != bytes.Length) return false;
    for (int i = 0; i < array.Length; i++)     
        if (array[i] != bytes[i]) return false;

    return true;
}
Run Code Online (Sandbox Code Playgroud)

请注意,将它设为通用会很好,但由于无法比较,因此肯定会花费一些性能:

public static bool ArrayEquals<T>(this T[] first, T[] second)
{
    // Reference equality and nullity checks for safety and efficiency
    if (first == second)
    {
        return true;
    }
    if (first == null || second == null)
    {
        return false;
    }
    if (first.Length != second.Length)
    {
        return false;
    }        
    EqualityComparer<T> comparer = EqualityComparer<T>.Default;
    for (int i = 0; i < first.Length; i++)
    {
        if (!comparer.Equals(first[i], second[i]))
        {
             return false;
        }
    }
    return true;
}
Run Code Online (Sandbox Code Playgroud)


小智 6

using System.Linq;

byte[] a = {1,2,3}; 
byte[] b = {1,2,3}; 
bool same = a.SequenceEqual(b);
Run Code Online (Sandbox Code Playgroud)