问题描述: 对于一个一维数组,将其中的元素逆置输出!
解决方法一: 前后端数据交换
object[] array = new object[] { 1,2,3,4,5,6,'x'}; for (int i = 0; i < array.Length / 2; i++) { object t = array[i]; array[i] = array[array.Length-1-i]; array[array.Length-1-i] = t; } for (int i = 0; i < array.Length; i++) { Console.Write(" " + array[i]); } Console.ReadKey();
结果 ,由于将数组定义为object,所以数组的元素可以是任意类型,但这样会有一个问题,就是数组要想比较大小的时候就麻烦了,可以考虑使用泛型来实现!
解决方法二:采用泛型实现
Msdn官方解释:泛型和数组
在 C# 2.0 以及更高版本中,下限为零的一维数组自动实现 IList<T>。这使您可以创建能够使用相同代码循环访问数组和其他集合类型的泛型方法。此技术主要对读取集合中的数据很有用。IList<T> 接口不能用于在数组中添加或移除元素。如果尝试对此上下文中的数组调用 IList<T> 方法(例如 RemoveAt),则将引发异常。
下面的代码示例演示带有 IList<T> 输入参数的单个泛型方法如何同时循环访问列表和数组,本例中为整数数组。
IList 属性如下:
static void Main(string[] args) { object[] array = new object[] { 1,2,3,4,5,6,'x'}; int[] array2 = new int[] { 1, 2, 3, 4, 5, 6, 7, 8 }; InversionArray(array); InversionArray(array2); PrintArray(array); PrintArray(array2); Console.ReadKey(); } private static void PrintArray<T>(IList<T> array) { for (int i = 0; i < array.Count; i++) //将之前的array.Length 改为array.Count; { Console.Write(" " + array[i]); } Console.WriteLine("打印完毕"); } private static void InversionArray<T>(IList<T> array) { for (int i = 0; i < array.Count/ 2; i++) { T t = array[i]; array[i] = array[array.Count - 1 - i]; array[array.Count - 1 - i] = t; } }
结果: