您现在的位置: 万盛学电脑网 >> 程序编程 >> 网络编程 >> 编程语言综合 >> 正文

C#使用自定义算法对数组进行反转操作的方法

作者:佚名    责任编辑:admin    更新时间:2022-06-22

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