本文主要介绍.NET Core(C#)中,使用数组的一些工具方法,包括设置数组的默认值,为数组的指定起启索引赋值,将Array 转成ArrayList,比较两个数组是否相等,数组的拷贝(copy)和toString()等方法,以及相关的示例代码。

1、设置数组默认值方法

        public static void Fill(byte[] array,byte defaultValue)
        {
            for (int i = 0; i < array.Length; i++)
            {
                array[i] = defaultValue;
            }
        }
        public static void Fill(char[] array, char defaultValue)
        {
            for (int i = 0; i < array.Length; i++)
            {
                array[i] = defaultValue;
            }
        }
        public static void Fill<T>(T[] array, T defaultValue)
        {
            for (int i = 0; i < array.Length; i++)
            {
                array[i] = defaultValue;
            }
        }
        public static void Fill(byte[] a, int fromIndex, int toIndex, byte val)
        {
            RangeCheck(a.Length, fromIndex, toIndex);
            for (int i = fromIndex; i < toIndex; i++)
                a[i] = val;
        }
        private static void RangeCheck(int length, int fromIndex, int toIndex)
        {
            if (fromIndex > toIndex)
            {
                throw new ArgumentException(
                    "fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ")");
            }
            if (fromIndex < 0)
            {
                throw new IndexOutOfRangeException("fromIndex(" + fromIndex + ")");
            }
            if (toIndex > length)
            {
                throw new IndexOutOfRangeException( "toIndex(" + toIndex + ")");
            }
        }
      public static void Fill(int[] array, byte defaultValue)
        {
            for (int i = 0; i < array.Length; i++)
            {
                array[i] = defaultValue;
            }
        }

2、Array 转成ArrayList

   public static ArrayList AsList(Array arr)
        {
            if (arr.Length <= 0)
                return new ArrayList();
            ArrayList al = new ArrayList(arr.Length);
            for (int i = 0; i < arr.Length; i++)
            {
                al.Add(arr.GetValue(i));
            }
            return al;
        }

3、比较两个数组是否相等

        public new static bool Equals(object a1, object b1)
        {
            if (a1 == null || b1 == null)
                return false;
            Array a = a1 as Array;
            Array b = b1 as Array;
            if (a.Length != b.Length)
                return false;
            for (int i = 0; i < a.Length; i++)
            {
                if (!a.GetValue(i).Equals(b.GetValue(i)))
                    return false;
            }
            return true;
        }
        public static bool Equals(Object[] a, Object[] a2)
        {
            if (a == a2)
                return true;
            if (a == null || a2 == null)
                return false;
            int length = a.Length;
            if (a2.Length != length)
                return false;
            for (int i = 0; i < length; i++)
            {
                Object o1 = a[i];
                Object o2 = a2[i];
                if (!(o1 == null ? o2 == null : o1.Equals(o2)))
                    return false;
            }
            return true;
        }
  public static bool DeepEquals(Object[] a1, Object[] a2) {
            if (a1 == a2)
                return true;
            if (a1 == null || a2==null)
                return false;
            int length = a1.Length;
            if (a2.Length != length)
                return false;
            for (int i = 0; i < length; i++) {
                Object e1 = a1[i];
                Object e2 = a2[i];
                if (e1 == e2)
                    continue;
                if (e1 == null)
                    return false;
                // Figure out whether the two elements are equal
                bool eq = DeepEquals0(e1, e2);
                if (!eq)
                    return false;
            }
            return true;
        }
        static bool DeepEquals0(Object e1, Object e2) {
            bool eq;
            if (e1 is Object[] && e2 is Object[])
                eq = DeepEquals ((Object[]) e1, (Object[]) e2);
            else if (e1 is byte[] && e2 is byte[])
                eq = Equals((byte[]) e1, (byte[]) e2);
            else if (e1 is short[] && e2 is short[])
                eq = Equals((short[]) e1, (short[]) e2);
            else if (e1 is int[] && e2 is int[])
                eq = Equals((int[]) e1, (int[]) e2);
            else if (e1 is long[] && e2 is long[])
                eq = Equals((long[]) e1, (long[]) e2);
            else if (e1 is char[] && e2 is char[])
                eq = Equals((char[]) e1, (char[]) e2);
            else if (e1 is float[] && e2 is float[])
                eq = Equals((float[]) e1, (float[]) e2);
            else if (e1 is double[] && e2 is double[])
                eq = Equals((double[]) e1, (double[]) e2);
            else if (e1 is bool[] && e2 is bool[])
                eq = Equals((bool[]) e1, (bool[]) e2);
            else
                eq = e1.Equals(e2);
            return eq;
        }

4、数组的拷贝方法

        public static void ArrayMoveWithin(Object[] array, int moveFrom, int moveTo, int numToMove)
        {
            // If we're not asked to do anything, return now
            if (numToMove <= 0) { return; }
            if (moveFrom == moveTo) { return; }
            // Check that the values supplied are valid
            if (moveFrom < 0 || moveFrom >= array.Length)
            {
                throw new ArgumentException("The moveFrom must be a valid array index");
            }
            if (moveTo < 0 || moveTo >= array.Length)
            {
                throw new ArgumentException("The moveTo must be a valid array index");
            }
            if (moveFrom + numToMove > array.Length)
            {
                throw new ArgumentException("Asked to move more entries than the array has");
            }
            if (moveTo + numToMove > array.Length)
            {
                throw new ArgumentException("Asked to move to a position that doesn't have enough space");
            }
            // Grab the bit to move 
            Object[] toMove = new Object[numToMove];
            Array.Copy(array, moveFrom, toMove, 0, numToMove);
            // Grab the bit to be shifted
            Object[] toShift;
            int shiftTo;
            if (moveFrom > moveTo)
            {
                // Moving to an earlier point in the array
                // Grab everything between the two points
                toShift = new Object[(moveFrom - moveTo)];
                Array.Copy(array, moveTo, toShift, 0, toShift.Length);
                shiftTo = moveTo + numToMove;
            }
            else
            {
                // Moving to a later point in the array
                // Grab everything from after the toMove block, to the new point
                toShift = new Object[(moveTo - moveFrom)];
                Array.Copy(array, moveFrom + numToMove, toShift, 0, toShift.Length);
                shiftTo = moveFrom;
            }
            // Copy the moved block to its new location
            Array.Copy(toMove, 0, array, moveTo, toMove.Length);
            // And copy the shifted block to the shifted location
            Array.Copy(toShift, 0, array, shiftTo, toShift.Length);
            // We're done - array will now have everything moved as required
        }
        public static byte[] CopyOf(byte[] source, int newLength)
        {
            byte[] result = new byte[newLength];
            Array.Copy(source, 0, result, 0,
                    Math.Min(source.Length, newLength));
            return result;
        }
        internal static int[] CopyOfRange(int[] original, int from, int to)
        {
            int newLength = to - from;
            if (newLength < 0)
                throw new ArgumentException(from + " > " + to);
            int[] copy = new int[newLength];
            Array.Copy(original, from, copy, 0,
                             Math.Min(original.Length - from, newLength));
            return copy;
        }
        internal static byte[] CopyOfRange(byte[] original, int from, int to)
        {
            int newLength = to - from;
            if (newLength < 0)
                throw new ArgumentException(from + " > " + to);
            byte[] copy = new byte[newLength];
            Array.Copy(original, from, copy, 0,
                             Math.Min(original.Length - from, newLength));
            return copy;
        }

5、工具类方法完整代码

using System;
using System.Collections;
using System.Text;
using System.Collections.Generic;
using NPOI.Util.Collections;

namespace CJAVAPY.Util
{
    public class Arrays
    {
        public static void Fill(byte[] array,byte defaultValue)
        {
            for (int i = 0; i < array.Length; i++)
            {
                array[i] = defaultValue;
            }
        }
        public static void Fill(char[] array, char defaultValue)
        {
            for (int i = 0; i < array.Length; i++)
            {
                array[i] = defaultValue;
            }
        }
        public static void Fill<T>(T[] array, T defaultValue)
        {
            for (int i = 0; i < array.Length; i++)
            {
                array[i] = defaultValue;
            }
        }
        public static void Fill(byte[] a, int fromIndex, int toIndex, byte val)
        {
            RangeCheck(a.Length, fromIndex, toIndex);
            for (int i = fromIndex; i < toIndex; i++)
                a[i] = val;
        }
        private static void RangeCheck(int length, int fromIndex, int toIndex)
        {
            if (fromIndex > toIndex)
            {
                throw new ArgumentException(
                    "fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ")");
            }
            if (fromIndex < 0)
            {
                throw new IndexOutOfRangeException("fromIndex(" + fromIndex + ")");
            }
            if (toIndex > length)
            {
                throw new IndexOutOfRangeException( "toIndex(" + toIndex + ")");
            }
        }
        public static ArrayList AsList(Array arr)
        {
            if (arr.Length <= 0)
                return new ArrayList();
            ArrayList al = new ArrayList(arr.Length);
            for (int i = 0; i < arr.Length; i++)
            {
                al.Add(arr.GetValue(i));
            }
            return al;
        }
        public static void Fill(int[] array, byte defaultValue)
        {
            for (int i = 0; i < array.Length; i++)
            {
                array[i] = defaultValue;
            }
        }
        public new static bool Equals(object a1, object b1)
        {
            if (a1 == null || b1 == null)
                return false;
            Array a = a1 as Array;
            Array b = b1 as Array;
            if (a.Length != b.Length)
                return false;
            for (int i = 0; i < a.Length; i++)
            {
                if (!a.GetValue(i).Equals(b.GetValue(i)))
                    return false;
            }
            return true;
        }
        public static bool Equals(Object[] a, Object[] a2)
        {
            if (a == a2)
                return true;
            if (a == null || a2 == null)
                return false;
            int length = a.Length;
            if (a2.Length != length)
                return false;
            for (int i = 0; i < length; i++)
            {
                Object o1 = a[i];
                Object o2 = a2[i];
                if (!(o1 == null ? o2 == null : o1.Equals(o2)))
                    return false;
            }
            return true;
        }
        public static void ArrayMoveWithin(Object[] array, int moveFrom, int moveTo, int numToMove)
        {
            // If we're not asked to do anything, return now
            if (numToMove <= 0) { return; }
            if (moveFrom == moveTo) { return; }
            // Check that the values supplied are valid
            if (moveFrom < 0 || moveFrom >= array.Length)
            {
                throw new ArgumentException("The moveFrom must be a valid array index");
            }
            if (moveTo < 0 || moveTo >= array.Length)
            {
                throw new ArgumentException("The moveTo must be a valid array index");
            }
            if (moveFrom + numToMove > array.Length)
            {
                throw new ArgumentException("Asked to move more entries than the array has");
            }
            if (moveTo + numToMove > array.Length)
            {
                throw new ArgumentException("Asked to move to a position that doesn't have enough space");
            }
            // Grab the bit to move 
            Object[] toMove = new Object[numToMove];
            Array.Copy(array, moveFrom, toMove, 0, numToMove);
            // Grab the bit to be shifted
            Object[] toShift;
            int shiftTo;
            if (moveFrom > moveTo)
            {
                // Moving to an earlier point in the array
                // Grab everything between the two points
                toShift = new Object[(moveFrom - moveTo)];
                Array.Copy(array, moveTo, toShift, 0, toShift.Length);
                shiftTo = moveTo + numToMove;
            }
            else
            {
                // Moving to a later point in the array
                // Grab everything from after the toMove block, to the new point
                toShift = new Object[(moveTo - moveFrom)];
                Array.Copy(array, moveFrom + numToMove, toShift, 0, toShift.Length);
                shiftTo = moveFrom;
            }
            // Copy the moved block to its new location
            Array.Copy(toMove, 0, array, moveTo, toMove.Length);
            // And copy the shifted block to the shifted location
            Array.Copy(toShift, 0, array, shiftTo, toShift.Length);

            // We're done - array will now have everything moved as required
        }
        public static byte[] CopyOf(byte[] source, int newLength)
        {
            byte[] result = new byte[newLength];
            Array.Copy(source, 0, result, 0,
                    Math.Min(source.Length, newLength));
            return result;
        }
        internal static int[] CopyOfRange(int[] original, int from, int to)
        {
            int newLength = to - from;
            if (newLength < 0)
                throw new ArgumentException(from + " > " + to);
            int[] copy = new int[newLength];
            Array.Copy(original, from, copy, 0,
                             Math.Min(original.Length - from, newLength));
            return copy;
        }
        internal static byte[] CopyOfRange(byte[] original, int from, int to)
        {
            int newLength = to - from;
            if (newLength < 0)
                throw new ArgumentException(from + " > " + to);
            byte[] copy = new byte[newLength];
            Array.Copy(original, from, copy, 0,
                             Math.Min(original.Length - from, newLength));
            return copy;
        }
        public static int HashCode(long[] a) {
            if (a == null)
                return 0;
            int result = 1;
            foreach (long element in a) {
                int elementHash = (int)(element ^ (Operator.UnsignedRightShift(element , 32)));
                result = 31 * result + elementHash;
            }
            return result;
        }
        public static int HashCode(int[] a) {
            if (a == null)
                return 0;
            int result = 1;
            foreach (int element in a)
                result = 31 * result + element;
            return result;
        }
        public static int HashCode(short[] a) {
            if (a == null)
                return 0;
            int result = 1;
            foreach (short element in a)
                result = 31 * result + element;
            return result;
        }
        public static int HashCode(char[] a) {
            if (a == null)
                return 0;
            int result = 1;
            foreach (char element in a)
                result = 31 * result + element;
            return result;
        }
        public static int HashCode(byte[] a) {
            if (a == null)
                return 0;
            int result = 1;
            foreach (byte element in a)
                result = 31 * result + element;
            return result;
        }
        public static int HashCode(bool[] a) {
            if (a == null)
                return 0;
            int result = 1;
            foreach (bool element in a)
                result = 31 * result + (element ? 1231 : 1237);
            return result;
        }
        public static int HashCode(float[] a) {
            if (a == null)
                return 0;
            int result = 1;
            foreach (float element in a)
            {
                result = 31 * result + BitConverter.ToInt32(BitConverter.GetBytes(element), 0);
            }
            return result;
        }
        public static int HashCode(double[] a) {
            if (a == null)
                return 0;
            int result = 1;
            foreach (double element in a) {
                long bits = BitConverter.DoubleToInt64Bits(element);
                result = 31 * result + (int)(bits ^ (Operator.UnsignedRightShift(bits, 32)));
            }
            return result;
        }
        public static int HashCode(Object[] a) {
            if (a == null)
                return 0;
            int result = 1;
            foreach (Object element in a)
                result = 31 * result + (element == null ? 0 : element.GetHashCode());
            return result;
        }
        public static int DeepHashCode(Object[] a) {
            if (a == null)
                return 0;
            int result = 1;
            foreach (Object element in a) {
                int elementHash = 0;
                if (element is Object[])
                    elementHash = DeepHashCode((Object[]) element);
                else if (element is byte[])
                    elementHash = HashCode((byte[]) element);
                else if (element is short[])
                    elementHash = HashCode((short[]) element);
                else if (element is int[])
                    elementHash = HashCode((int[]) element);
                else if (element is long[])
                    elementHash = HashCode((long[]) element);
                else if (element is char[])
                    elementHash = HashCode((char[]) element);
                else if (element is float[])
                    elementHash = HashCode((float[]) element);
                else if (element is double[])
                    elementHash = HashCode((double[]) element);
                else if (element is bool[])
                    elementHash = HashCode((bool[]) element);
                else if (element != null)
                    elementHash = element.GetHashCode();
                result = 31 * result + elementHash;
            }
            return result;
        }
        public static bool DeepEquals(Object[] a1, Object[] a2) {
            if (a1 == a2)
                return true;
            if (a1 == null || a2==null)
                return false;
            int length = a1.Length;
            if (a2.Length != length)
                return false;
            for (int i = 0; i < length; i++) {
                Object e1 = a1[i];
                Object e2 = a2[i];
                if (e1 == e2)
                    continue;
                if (e1 == null)
                    return false;
                // Figure out whether the two elements are equal
                bool eq = DeepEquals0(e1, e2);
                if (!eq)
                    return false;
            }
            return true;
        }
        static bool DeepEquals0(Object e1, Object e2) {
            bool eq;
            if (e1 is Object[] && e2 is Object[])
                eq = DeepEquals ((Object[]) e1, (Object[]) e2);
            else if (e1 is byte[] && e2 is byte[])
                eq = Equals((byte[]) e1, (byte[]) e2);
            else if (e1 is short[] && e2 is short[])
                eq = Equals((short[]) e1, (short[]) e2);
            else if (e1 is int[] && e2 is int[])
                eq = Equals((int[]) e1, (int[]) e2);
            else if (e1 is long[] && e2 is long[])
                eq = Equals((long[]) e1, (long[]) e2);
            else if (e1 is char[] && e2 is char[])
                eq = Equals((char[]) e1, (char[]) e2);
            else if (e1 is float[] && e2 is float[])
                eq = Equals((float[]) e1, (float[]) e2);
            else if (e1 is double[] && e2 is double[])
                eq = Equals((double[]) e1, (double[]) e2);
            else if (e1 is bool[] && e2 is bool[])
                eq = Equals((bool[]) e1, (bool[]) e2);
            else
                eq = e1.Equals(e2);
            return eq;
        }
        public static String ToString(long[] a) {
            if (a == null)
                return "null";
            int iMax = a.Length - 1;
            if (iMax == -1)
                return "[]";
            StringBuilder b = new StringBuilder();
            b.Append('[');
            for (int i = 0; ; i++) {
                b.Append(a[i]);
                if (i == iMax)
                    return b.Append(']').ToString();
                b.Append(", ");
            }
        }
        public static String ToString(int[] a) {
            if (a == null)
                return "null";
            int iMax = a.Length - 1;
            if (iMax == -1)
                return "[]";
            StringBuilder b = new StringBuilder();
            b.Append('[');
            for (int i = 0; ; i++) {
                b.Append(a[i]);
                if (i == iMax)
                    return b.Append(']').ToString();
                b.Append(", ");
            }
        }
        public static String ToString(short[] a) {
            if (a == null)
                return "null";
            int iMax = a.Length - 1;
            if (iMax == -1)
                return "[]";
            StringBuilder b = new StringBuilder();
            b.Append('[');
            for (int i = 0; ; i++) {
                b.Append(a[i]);
                if (i == iMax)
                    return b.Append(']').ToString();
                b.Append(", ");
            }
        }
        public static String ToString(char[] a) {
            if (a == null)
                return "null";
            int iMax = a.Length - 1;
            if (iMax == -1)
                return "[]";
            StringBuilder b = new StringBuilder();
            b.Append('[');
            for (int i = 0; ; i++) {
                b.Append(a[i]);
                if (i == iMax)
                    return b.Append(']').ToString();
                b.Append(", ");
            }
        }
        public static String ToString(byte[] a) {
            if (a == null)
                return "null";
            int iMax = a.Length - 1;
            if (iMax == -1)
                return "[]";
            StringBuilder b = new StringBuilder();
            b.Append('[');
            for (int i = 0; ; i++) {
                b.Append(a[i]);
                if (i == iMax)
                    return b.Append(']').ToString();
                b.Append(", ");
            }
        }
        public static String ToString(bool[] a) {
            if (a == null)
                return "null";
            int iMax = a.Length - 1;
            if (iMax == -1)
                return "[]";
            StringBuilder b = new StringBuilder();
            b.Append('[');
            for (int i = 0; ; i++) {
                b.Append(a[i]);
                if (i == iMax)
                    return b.Append(']').ToString();
                b.Append(", ");
            }
        }
        public static String ToString(float[] a) {
            if (a == null)
                return "null";
            int iMax = a.Length - 1;
            if (iMax == -1)
                return "[]";
            StringBuilder b = new StringBuilder();
            b.Append('[');
            for (int i = 0; ; i++) {
                b.Append(a[i]);
                if (i == iMax)
                    return b.Append(']').ToString();
                b.Append(", ");
            }
        }
        public static String ToString(double[] a) {
            if (a == null)
                return "null";
            int iMax = a.Length - 1;
            if (iMax == -1)
                return "[]";
            StringBuilder b = new StringBuilder();
            b.Append('[');
            for (int i = 0; ; i++) {
                b.Append(a[i]);
                if (i == iMax)
                    return b.Append(']').ToString();
                b.Append(", ");
            }
        }
        public static String DeepToString(Object[] a) {
            if (a == null)
                return "null";
            int bufLen = 20 * a.Length;
            if (a.Length != 0 && bufLen <= 0)
                bufLen = Int32.MaxValue;
            StringBuilder buf = new StringBuilder(bufLen);
            DeepToString(a, buf, new NPOI.Util.Collections.HashSet<Object[]>());
            return buf.ToString();
        }
        private static void DeepToString(Object[] a, StringBuilder buf,
                                         NPOI.Util.Collections.HashSet<Object[]> dejaVu)
        {
            if (a == null)
            {
                buf.Append("null");
                return;
            }
            int iMax = a.Length - 1;
            if (iMax == -1)
            {
                buf.Append("[]");
                return;
            }
            dejaVu.Add(a);
            buf.Append('[');
            for (int i = 0; ; i++)
            {
                Object element = a[i];
                if (element == null)
                {
                    buf.Append("null");
                }
                else
                {
                    Type eClass = element.GetType();
                    //Class<?> eClass = element.Class;
                    if (eClass.IsArray)
                    {
                        if (eClass == typeof(byte[]))
                            buf.Append(ToString((byte[])element));
                        else if (eClass == typeof(short[]))
                            buf.Append(ToString((short[])element));
                        else if (eClass == typeof(int[]))
                            buf.Append(ToString((int[])element));
                        else if (eClass == typeof(long[]))
                            buf.Append(ToString((long[])element));
                        else if (eClass == typeof(char[]))
                            buf.Append(ToString((char[])element));
                        else if (eClass == typeof(float[]))
                            buf.Append(ToString((float[])element));
                        else if (eClass == typeof(double[]))
                            buf.Append(ToString((double[])element));
                        else if (eClass == typeof(bool[]))
                            buf.Append(ToString((bool[])element));
                        else
                        { // element is an array of object references
                            if (dejaVu.Contains((element as object[])))
                                buf.Append("[...]");
                            else
                                DeepToString((Object[])element, buf, dejaVu);
                        }
                    }
                    else
                    {  // element is non-null and not an array
                        buf.Append(element.ToString());
                    }
                }
                if (i == iMax)
                    break;
                buf.Append(", ");
            }
            buf.Append(']');
            dejaVu.Remove(a);
        }
        public static String ToString(Object[] a)
        {
            if (a == null)
                return "null";
            int iMax = a.Length - 1;
            if (iMax == -1)
                return "[]";
            StringBuilder b = new StringBuilder();
            b.Append('[');
            for (int i = 0; ; i++)
            {
                b.Append(a[i].ToString());
                if (i == iMax)
                    return b.Append(']').ToString();
                b.Append(", ");
            }
        }
    }
}

相关文档:https://github.com/dotnetcore/NPOI

推荐文档