C#方法的应用练习,Reverse

编写一个程序,定义一个静态方法Reverse,在Main中随机产生一个数组,并作为参数传递给Reverse,实现数组中存储的数据顺序反转,将反转数组返回给Main中并输出。

C#中,实现数组反转的方法有很多种,比如:循环遍历,.NET内置的LINQ静态扩展方法等,示例如下:

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApp2
{
    public class MyProgram
    {
        static void Main(string[] args)
        {
            int Min = 0;
            int Max = 100;
            int[] arr = new int[5];

            Random randNum = new Random();
            for (int i = 0; i < arr.Length; i++)
            {
                arr[i] = randNum.Next(Min, Max);
            }

            Console.WriteLine(JsonConvert.SerializeObject(arr));
            // 方式一
            var result = Reverse(arr);
            // 输出结果
            Console.WriteLine(JsonConvert.SerializeObject(result));

            // 方式二
            var result2 = arr.ReverseMethod();
            // 输出结果
            Console.WriteLine(JsonConvert.SerializeObject(result2));

            // 方式三 .NET内置的LINQ扩展方法
            var result3 = arr.Reverse();
            // 输出结果
            Console.WriteLine(JsonConvert.SerializeObject(result3));


            Console.ReadKey();
        }
        static int[] Reverse(int[] arr)
        {
            var newArray = new List<int>();
            for (int i = arr.Length - 1; i >= 0; i--)
            {
                newArray.Add(arr[i]);
            }
            return newArray.ToArray();
        }


    }

    public static class Ex
    {
        /// <summary>
        /// 静态扩展方法
        /// </summary>
        /// <param name="array"></param>
        /// <returns></returns>
        public static IEnumerable<int> ReverseMethod(this int[] array)
        {
            for (int i = array.Length - 1; i >= 0; i--)
            {
                yield return array[i];
            }
        }
    }
}

运行结果:

[25,87,65,13,15]
[15,13,65,87,25]
[15,13,65,87,25]
[15,13,65,87,25]