C#的Array對象自帶反轉功能,但是下面的代碼完全通過自定義的算法來實現數組反轉
代碼如下:
public static void ReverseArray<T>(this T[] inputArray)
{
T temp = default(T);
if (inputArray == null)
throw new ArgumentNullException("inputArray is empty");
if (inputArray.Length > 0)
{
for (int counter = 0; counter < (inputArray.Length / 2); counter++)
{
temp = inputArray[counter];
inputArray[counter] = inputArray[inputArray.Length - counter - 1];
inputArray[inputArray.Length - counter - 1] = temp;
}
}
else
{
Trace.WriteLine("Reversal not needed");
}
}