在C#中比较数组

我试图互相比较两个数组。我尝试了这段代码,并收到以下错误。


static bool ArraysEqual(Array a1, Array a2)

{

    if (a1 == a2)

        return true;


    if (a1 == null || a2 == null)

        return false;


    if (a1.Length != a2.Length)

        return false;


    IList list1 = a1, list2 = a2; //error CS0305: Using the generic type 'System.Collections.Generic.IList<T>' requires '1' type arguments

    for (int i = 0; i < a1.Length; i++)

    {

        if (!Object.Equals(list1[i], list2[i])) //error CS0021: Cannot apply indexing with [] to an expression of type 'IList'(x2)

            return false;

    }

    return true;

}

为什么会出现该错误?我选择了一种技术含量低的解决方案,并且效果很好,但是每种类型我都需要复制/粘贴几次。


static bool ArraysEqual(byte[] a1, byte[] a2)

{

    if (a1 == a2)

        return true;


    if (a1 == null || a2 == null)

        return false;


    if (a1.Length != a2.Length)

        return false;


    for (int i = 0; i < a1.Length; i++)

    {

        if (a1[i] != a2[i])

            return false;

    }

    return true;

}


慕勒3428872
浏览 599回答 3
3回答

达令说

假设您有LINQ可用并且对性能不太在意,则最简单的事情如下:var arraysAreEqual = Enumerable.SequenceEqual(a1, a2);实际上,可能值得用Reflector或ILSpy检查这些SequenceEqual方法的实际作用,因为无论如何它都可以针对数组值的特殊情况进行优化!

MM们

“为什么我会收到该错误?” -可能using System.Collections;文件的顶部没有“ ”-只有“ using System.Collections.Generic;”-但是,泛型可能更安全-参见下文:static bool ArraysEqual<T>(T[] a1, T[] a2){&nbsp; &nbsp; if (ReferenceEquals(a1,a2))&nbsp; &nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; if (a1 == null || a2 == null)&nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; if (a1.Length != a2.Length)&nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; EqualityComparer<T> comparer = EqualityComparer<T>.Default;&nbsp; &nbsp; for (int i = 0; i < a1.Length; i++)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if (!comparer.Equals(a1[i], a2[i])) return false;&nbsp; &nbsp; }&nbsp; &nbsp; return true;}

千巷猫影

对于.NET 4.0及更高版本,您可以使用StructuralComparisons类型比较数组或元组中的元素:object[] a1 = { "string", 123, true };object[] a2 = { "string", 123, true };Console.WriteLine (a1 == a2);&nbsp; &nbsp; &nbsp; &nbsp; // False (because arrays is reference types)Console.WriteLine (a1.Equals (a2));&nbsp; // False (because arrays is reference types)IStructuralEquatable se1 = a1;//Next returns TrueConsole.WriteLine (se1.Equals (a2, StructuralComparisons.StructuralEqualityComparer));&nbsp;
打开App,查看更多内容
随时随地看视频慕课网APP