Array.Reverse()方法背后的逻辑

时间:2010-05-19 14:23:42

标签: c# .net reverse

public static void Reverse(Array array,int index,int length)背后的原生逻辑工作是什么;

3 个答案:

答案 0 :(得分:5)

您可以使用.NET Reflector

[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是一种本机方法,有时可以更快地执行相同的操作。

答案 1 :(得分:2)

从起点index循环到范围的中间,index + length/2,用array[i]交换每个array[index + length - i - 1]

答案 2 :(得分:0)

有关本机方法“ TrySZReverse”的一些详细信息

从coreclr([1] [2])的相关代码中,TrySZReverse处理原始类型的数组,并且反向算法与Array.Reverse相同:

代码引用

    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--;
        }
    }

并且前缀“ SZ”似乎代表“单维零终止”。