• System.Array与string[], int[]的区别及用途


    经常用string[], int[]这些数组, 今天偶然发现还有一个System.Array类, 它的声明如下:

    public abstract class Array : ICloneable, IList, ICollection, IEnumerable, IStructuralComparable, IStructuralEquatable

    看来它是一个抽象类.

    查一下msdn, 发现它的用途如下:

    "提供创建、操作、搜索和排序数组的方法,因而在公共语言运行时中用作所有数组的基类。"
    "Array 类是支持数组的语言实现的基类。但是,只有系统和编译器能够从 Array 类显式派生。用户应当使用由语言提供的数组构造。"

    自己写代码试了一下, 确实如上所述, 不能继承Array这个抽象类,

    Array的使用方法举例:

                Array abc = Array.CreateInstance(typeof(string), 3);
                abc.SetValue("lzd1", 0);
                abc.SetValue("lzd2", 1);
                abc.SetValue("lzd3", 2);
                for (int i = 0; i < abc.Length; i++)
                {
                    Console.WriteLine(abc.GetValue(i));
                }

    看这代码,觉得和string[], int[]的本质是一样的,就是繁琐些,难怪msdn说它是所有数组的基类,但是用refactor翻译一段string[],int[]的代码,发现编译后并不翻译成Array,不知道内部它们之间是怎么转换的,先不管这也罢,反正最重要的思考一下Array的作用和用途在哪里?毕竟直接定义的数组比Array.CreateInstance()要简单得多。

    试一下就可以明白,直接定义的数组不支持排序等操作,如果定义了string[], int[],想要排序,就可以用Array抽象类中的Sort方法了,我想,这是它很有用的一点了。

                string[] def = new string[] { "lzd7", "lzd5", "lzd6" };
                for (int i = 0; i < def.Length; i++)
                {
                    Console.WriteLine(def[i]);
                }
                Array.Sort(def);
                for (int i = 0; i < def.Length; i++)
                {
                    Console.WriteLine(def[i]);
                }

    推荐资料:
    1.C#:System.Array简单使用。
    http://hi.baidu.com/yehaizi_2008/blog/item/dd57aada9a8ff4d7b6fd4880.html
    2.Array 类

    http://msdn.microsoft.com/zh-cn/library/system.array.aspx

    3.用refactor得到Array类的源代码如下, 方法都折叠未展开: 

    [Serializable, ComVisible(true)]
    public abstract class Array : ICloneable, IList, ICollection, IEnumerable, IStructuralComparable, IStructuralEquatable
    {
        // Methods
        internal Array();
        public static ReadOnlyCollection<T> AsReadOnly<T>(T[] array);
        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
        public static int BinarySearch<T>(T[] array, T value);
        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
        public static int BinarySearch(Array array, object value);
        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
        public static int BinarySearch(Array array, object value, IComparer comparer);
        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
        public static int BinarySearch<T>(T[] array, T value, IComparer<T> comparer);
        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
        public static int BinarySearch(Array array, int index, int length, object value);
        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
        public static int BinarySearch<T>(T[] array, int index, int length, T value);
        [SecuritySafeCritical, ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
        public static int BinarySearch<T>(T[] array, int index, int length, T value, IComparer<T> comparer);
        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail), SecuritySafeCritical]
        public static int BinarySearch(Array array, int index, int length, object value, IComparer comparer);
        [MethodImpl(MethodImplOptions.InternalCall), SecuritySafeCritical, ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
        public static extern void Clear(Array array, int index, int length);
        [SecuritySafeCritical]
        public object Clone();
        internal static int CombineHashCodes(int h1, int h2);
        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success), SecuritySafeCritical]
        public static void ConstrainedCopy(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length);
        public static TOutput[] ConvertAll<TInput, TOutput>(TInput[] array, Converter<TInput, TOutput> converter);
        [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail), SecuritySafeCritical]
        public static void Copy(Array sourceArray, Array destinationArray, int length);
        [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
        public static void Copy(Array sourceArray, Array destinationArray, long length);
        [SecuritySafeCritical, ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
        public static void Copy(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length);
        [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
        public static void Copy(Array sourceArray, long sourceIndex, Array destinationArray, long destinationIndex, long length);
        [MethodImpl(MethodImplOptions.InternalCall), SecurityCritical, ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
        internal static extern void Copy(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length, bool reliable);
        public void CopyTo(Array array, int index);
        [ComVisible(false)]
        public void CopyTo(Array array, long index);
        [SecuritySafeCritical]
        public static Array CreateInstance(Type elementType, int length);
        public static Array CreateInstance(Type elementType, params long[] lengths);
        [SecuritySafeCritical]
        public static Array CreateInstance(Type elementType, params int[] lengths);
        [SecuritySafeCritical]
        public static Array CreateInstance(Type elementType, int length1, int length2);
        [SecuritySafeCritical]
        public static Array CreateInstance(Type elementType, int[] lengths, int[] lowerBounds);
        [SecuritySafeCritical]
        public static Array CreateInstance(Type elementType, int length1, int length2, int length3);
        public static bool Exists<T>(T[] array, Predicate<T> match);
        public static T Find<T>(T[] array, Predicate<T> match);
        public static T[] FindAll<T>(T[] array, Predicate<T> match);
        public static int FindIndex<T>(T[] array, Predicate<T> match);
        public static int FindIndex<T>(T[] array, int startIndex, Predicate<T> match);
        public static int FindIndex<T>(T[] array, int startIndex, int count, Predicate<T> match);
        public static T FindLast<T>(T[] array, Predicate<T> match);
        public static int FindLastIndex<T>(T[] array, Predicate<T> match);
        public static int FindLastIndex<T>(T[] array, int startIndex, Predicate<T> match);
        public static int FindLastIndex<T>(T[] array, int startIndex, int count, Predicate<T> match);
        public static void ForEach<T>(T[] array, Action<T> action);
        [MethodImpl(MethodImplOptions.InternalCall), SecurityCritical, ForceTokenStabilization, ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
        internal extern int GetDataPtrOffsetInternal();
        public IEnumerator GetEnumerator();
        [MethodImpl(MethodImplOptions.InternalCall), SecuritySafeCritical]
        public extern int GetLength(int dimension);
        [ComVisible(false)]
        public long GetLongLength(int dimension);
        [MethodImpl(MethodImplOptions.InternalCall), ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success), SecuritySafeCritical]
        public extern int GetLowerBound(int dimension);
        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
        private static int GetMedian(int low, int hi);
        [MethodImpl(MethodImplOptions.InternalCall), ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success), SecuritySafeCritical]
        public extern int GetUpperBound(int dimension);
        [SecuritySafeCritical]
        public object GetValue(int index);
        [SecuritySafeCritical]
        public object GetValue(params int[] indices);
        [ComVisible(false)]
        public object GetValue(long index);
        [ComVisible(false)]
        public object GetValue(params long[] indices);
        [SecuritySafeCritical]
        public object GetValue(int index1, int index2);
        [ComVisible(false)]
        public object GetValue(long index1, long index2);
        [SecuritySafeCritical]
        public object GetValue(int index1, int index2, int index3);
        [ComVisible(false)]
        public object GetValue(long index1, long index2, long index3);
        public static int IndexOf<T>(T[] array, T value);
        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
        public static int IndexOf(Array array, object value);
        public static int IndexOf<T>(T[] array, T value, int startIndex);
        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
        public static int IndexOf(Array array, object value, int startIndex);
        public static int IndexOf<T>(T[] array, T value, int startIndex, int count);
        [SecuritySafeCritical, ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
        public static int IndexOf(Array array, object value, int startIndex, int count);
        [MethodImpl(MethodImplOptions.InternalCall), SecuritySafeCritical]
        public extern void Initialize();
        [MethodImpl(MethodImplOptions.InternalCall), SecurityCritical]
        private static extern unsafe Array InternalCreate(void* elementType, int rank, int* pLengths, int* pLowerBounds);
        [MethodImpl(MethodImplOptions.InternalCall), SecurityCritical]
        private extern unsafe void InternalGetReference(void* elemRef, int rank, int* pIndices);
        [MethodImpl(MethodImplOptions.InternalCall), SecurityCritical]
        private static extern unsafe void InternalSetValue(void* target, object value);
        public static int LastIndexOf<T>(T[] array, T value);
        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
        public static int LastIndexOf(Array array, object value);
        public static int LastIndexOf<T>(T[] array, T value, int startIndex);
        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
        public static int LastIndexOf(Array array, object value, int startIndex);
        [SecuritySafeCritical, ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
        public static int LastIndexOf(Array array, object value, int startIndex, int count);
        public static int LastIndexOf<T>(T[] array, T value, int startIndex, int count);
        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
        public static void Resize<T>(ref T[] array, int newSize);
        [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
        public static void Reverse(Array array);
        [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail), SecuritySafeCritical]
        public static void Reverse(Array array, int index, int length);
        [SecuritySafeCritical]
        public void SetValue(object value, params int[] indices);
        [SecuritySafeCritical]
        public void SetValue(object value, int index);
        [ComVisible(false)]
        public void SetValue(object value, long index);
        [ComVisible(false)]
        public void SetValue(object value, params long[] indices);
        [SecuritySafeCritical]
        public void SetValue(object value, int index1, int index2);
        [ComVisible(false)]
        public void SetValue(object value, long index1, long index2);
        [SecuritySafeCritical]
        public void SetValue(object value, int index1, int index2, int index3);
        [ComVisible(false)]
        public void SetValue(object value, long index1, long index2, long index3);
        [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
        public static void Sort<T>(T[] array);
        [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
        public static void Sort(Array array);
        [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
        public static void Sort(Array keys, Array items);
        [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
        public static void Sort<T>(T[] array, IComparer<T> comparer);
        [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
        public static void Sort(Array array, IComparer comparer);
        public static void Sort<T>(T[] array, Comparison<T> comparison);
        [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
        public static void Sort<TKey, TValue>(TKey[] keys, TValue[] items);
        [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
        public static void Sort<T>(T[] array, int index, int length);
        [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
        public static void Sort(Array array, int index, int length);
        [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
        public static void Sort<TKey, TValue>(TKey[] keys, TValue[] items, IComparer<TKey> comparer);
        [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
        public static void Sort(Array keys, Array items, IComparer comparer);
        [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail), SecuritySafeCritical]
        public static void Sort<T>(T[] array, int index, int length, IComparer<T> comparer);
        [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
        public static void Sort(Array keys, Array items, int index, int length);
        [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
        public static void Sort<TKey, TValue>(TKey[] keys, TValue[] items, int index, int length);
        [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
        public static void Sort(Array array, int index, int length, IComparer comparer);
        [SecuritySafeCritical, ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
        public static void Sort<TKey, TValue>(TKey[] keys, TValue[] items, int index, int length, IComparer<TKey> comparer);
        [SecuritySafeCritical, ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
        public static void Sort(Array keys, Array items, int index, int length, IComparer comparer);
        int IList.Add(object value);
        void IList.Clear();
        bool IList.Contains(object value);
        int IList.IndexOf(object value);
        void IList.Insert(int index, object value);
        void IList.Remove(object value);
        void IList.RemoveAt(int index);
        int IStructuralComparable.CompareTo(object other, IComparer comparer);
        bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer);
        int IStructuralEquatable.GetHashCode(IEqualityComparer comparer);
        public static bool TrueForAll<T>(T[] array, Predicate<T> match);
        [MethodImpl(MethodImplOptions.InternalCall), ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail), SecurityCritical]
        private static extern bool TrySZBinarySearch(Array sourceArray, int sourceIndex, int count, object value, out int retVal);
        [MethodImpl(MethodImplOptions.InternalCall), SecurityCritical, ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
        private static extern bool TrySZIndexOf(Array sourceArray, int sourceIndex, int count, object value, out int retVal);
        [MethodImpl(MethodImplOptions.InternalCall), SecurityCritical, ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
        private static extern bool TrySZLastIndexOf(Array sourceArray, int sourceIndex, int count, object value, out int retVal);
        [MethodImpl(MethodImplOptions.InternalCall), SecurityCritical, ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
        private static extern bool TrySZReverse(Array array, int index, int count);
        [MethodImpl(MethodImplOptions.InternalCall), ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail), SecurityCritical]
        private static extern bool TrySZSort(Array keys, Array items, int left, int right);
        [SecurityCritical, PermissionSet(SecurityAction.Assert, Unrestricted=true)]
        internal static Array UnsafeCreateInstance(Type elementType, params int[] lengths);
        [SecurityCritical, PermissionSet(SecurityAction.Assert, Unrestricted=true)]
        internal static Array UnsafeCreateInstance(Type elementType, int length);
        [SecurityCritical, PermissionSet(SecurityAction.Assert, Unrestricted=true)]
        internal static Array UnsafeCreateInstance(Type elementType, int[] lengths, int[] lowerBounds);
        [SecurityCritical, PermissionSet(SecurityAction.Assert, Unrestricted=true)]
        internal static Array UnsafeCreateInstance(Type elementType, int length1, int length2);

        // Properties
        public bool IsFixedSize { get; }
        public bool IsReadOnly { get; }
        public bool IsSynchronized { get; }
        public int Length { [MethodImpl(MethodImplOptions.InternalCall), ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success), SecuritySafeCritical] get; }
        [ComVisible(false)]
        public long LongLength { [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] get; }
        public int Rank { [MethodImpl(MethodImplOptions.InternalCall), ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success), SecuritySafeCritical] get; }
        public object SyncRoot { get; }
        int ICollection.Count { get; }
        object IList.this[int index] { get; set; }

        // Nested Types
        [Serializable]
        private sealed class ArrayEnumerator : IEnumerator, ICloneable
        {
            // Fields
            private bool _complete;
            private int[] _indices;
            private Array array;
            private int endIndex;
            private int index;
            private int startIndex;

            // Methods
            internal ArrayEnumerator(Array array, int index, int count);
            [SecuritySafeCritical]
            public object Clone();
            private void IncArray();
            public bool MoveNext();
            public void Reset();

            // Properties
            public object Current { get; }
        }

        internal sealed class FunctorComparer<T> : IComparer<T>
        {
            // Fields
            private Comparer<T> c;
            private Comparison<T> comparison;

            // Methods
            public FunctorComparer(Comparison<T> comparison);
            public int Compare(T x, T y);
        }

        [StructLayout(LayoutKind.Sequential)]
        private struct SorterGenericArray
        {
            private Array keys;
            private Array items;
            private IComparer comparer;
            internal SorterGenericArray(Array keys, Array items, IComparer comparer);
            internal void SwapIfGreaterWithItems(int a, int b);
            internal void QuickSort(int left, int right);
        }

        [StructLayout(LayoutKind.Sequential)]
        private struct SorterObjectArray
        {
            private object[] keys;
            private object[] items;
            private IComparer comparer;
            internal SorterObjectArray(object[] keys, object[] items, IComparer comparer);
            internal void SwapIfGreaterWithItems(int a, int b);
            internal void QuickSort(int left, int right);
        }

        [Serializable]
        private sealed class SZArrayEnumerator : IEnumerator, ICloneable
        {
            // Fields
            private Array _array;
            private int _endIndex;
            private int _index;

            // Methods
            internal SZArrayEnumerator(Array array);
            [SecuritySafeCritical]
            public object Clone();
            public bool MoveNext();
            public void Reset();

            // Properties
            public object Current { get; }
        }
    }

    4.其中Sort方法展开如下:

    [SecuritySafeCritical, ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
    public static void Sort(Array keys, Array items, int index, int length, IComparer comparer)
    {
        if (keys == null)
        {
            throw new ArgumentNullException("keys");
        }
        if ((keys.Rank != 1) || ((items != null) && (items.Rank != 1)))
        {
            throw new RankException(Environment.GetResourceString("Rank_MultiDimNotSupported"));
        }
        if ((items != null) && (keys.GetLowerBound(0) != items.GetLowerBound(0)))
        {
            throw new ArgumentException(Environment.GetResourceString("Arg_LowerBoundsMustMatch"));
        }
        if ((index < keys.GetLowerBound(0)) || (length < 0))
        {
            throw new ArgumentOutOfRangeException((length < 0) ? "length" : "index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
        }
        if (((keys.Length - (index - keys.GetLowerBound(0))) < length) || ((items != null) && ((index - items.GetLowerBound(0)) > (items.Length - length))))
        {
            throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
        }
        if ((length > 1) && (((comparer != Comparer.Default) && (comparer != null)) || !TrySZSort(keys, items, index, (index + length) - 1)))
        {
            object[] objArray = keys as object[];
            object[] objArray2 = null;
            if (objArray != null)
            {
                objArray2 = items as object[];
            }
            if ((objArray != null) && ((items == null) || (objArray2 != null)))
            {
                new SorterObjectArray(objArray, objArray2, comparer).QuickSort(index, (index + length) - 1);
            }
            else
            {
                new SorterGenericArray(keys, items, comparer).QuickSort(index, (index + length) - 1);
            }
        }
    }

  • 相关阅读:
    阿里云技术专家杨泽强:弹性计算云上可观测能力构建
    云服务器ECS老用户专享,10余款实例新购低至3.6折
    重磅大咖来袭!阿里云生命科学与智能计算峰会精彩内容剧透
    阿里云技术专家秦隆:可靠性保障必备——云上如何进行混沌工程?
    《分布式云最佳实践》分论坛,8 月 11 日深圳见
    阿里云技术专家郝晨栋:云上可观测能力——问题的发现与定位实践
    十分钟生成影视级室内设计效果,红星美凯龙设计云如何升级传统家居行业
    阿里云技术专家邓青琳:云上跨可用区容灾和异地多活最佳实践
    本地化、低时延、绿色低碳:阿里云正式启用福州数据中心
    Triangle(bitset)
  • 原文地址:https://www.cnblogs.com/liuzhendong/p/2328647.html
Copyright © 2020-2023  润新知