什么是public static void Reverse(Array array,int index,int length)背后的原生逻辑工作;
您可以使用.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是一种本机方法,有时可以更快地执行相同的操作。
从起点index
循环到范围的中间,index + length/2
,用array[i]
交换每个array[index + length - i - 1]
。
关于本机方法“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”似乎代表“单维零终止”。