Logic behind the Array.Reverse() method

微笑、不失礼 提交于 2019-12-02 08:40:06

You can use .NET Reflector for that:

[ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
public static void Reverse(Array array, int index, int length)
{
    if (array == null)
    {
        throw new ArgumentNullException("array");
    }
    if ((index < array.GetLowerBound(0)) || (length < 0))
    {
        throw new ArgumentOutOfRangeException((index < 0) ? "index" : "length", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
    }
    if ((array.Length - (index - array.GetLowerBound(0))) < length)
    {
        throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
    }
    if (array.Rank != 1)
    {
        throw new RankException(Environment.GetResourceString("Rank_MultiDimNotSupported"));
    }
    if (!TrySZReverse(array, index, length))
    {
        int num = index;
        int num2 = (index + length) - 1;
        object[] objArray = array as object[];
        if (objArray == null)
        {
            while (num < num2)
            {
                object obj3 = array.GetValue(num);
                array.SetValue(array.GetValue(num2), num);
                array.SetValue(obj3, num2);
                num++;
                num2--;
            }
        }
        else
        {
            while (num < num2)
            {
                object obj2 = objArray[num];
                objArray[num] = objArray[num2];
                objArray[num2] = obj2;
                num++;
                num2--;
            }
        }
    }
}

TrySZReverse is a native method that can sometimes do the same thing only faster.

Loop from the starting point, index, to the middle of the range, index + length/2, swapping each array[i] with array[index + length - i - 1].

Some details about the native method "TrySZReverse"

from the related codes from coreclr([1][2]), TrySZReverse handles the array of primitive types, and the reverse algorithm is the same as Array.Reverse :

codes quotation

    static void Reverse(KIND array[], UINT32 index, UINT32 count) {
        LIMITED_METHOD_CONTRACT;

        _ASSERTE(array != NULL);
        if (count == 0) {
            return;
        }
        UINT32 i = index;
        UINT32 j = index + count - 1;
        while(i < j) {
            KIND temp = array[i];
            array[i] = array[j];
            array[j] = temp;
            i++;
            j--;
        }
    }

and the prefix "SZ" seems stands for "single-dimension zero-terminated".

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!