雖然 Array.Reverse 內建反轉功能,但透過自訂演算法可深入理解原地反轉邏輯。以下為泛型擴充方法實作:
public static void ReverseArray<T>(this T[] inputArray)
{
if (inputArray == null)
throw new ArgumentNullException("inputArray is empty");
if (inputArray.Length > 0)
{
for (int i = 0; i < inputArray.Length / 2; i++)
{
T temp = inputArray[i];
inputArray[i] = inputArray[inputArray.Length - i - 1];
inputArray[inputArray.Length - i - 1] = temp;
}
}
else
{
System.Diagnostics.Trace.WriteLine("Reversal not needed");
}
}
T 支援任意型別陣列。int[] arr = { 1, 2, 3, 4, 5 };
arr.ReverseArray(); // arr 變為 {5, 4, 3, 2, 1}