C#创建数组的方法与java相同,不过多介绍

  1. using System;
  2. namespace ArrayApplication
  3. {
  4. class MyArray
  5. {
  6. static void Main(string[] args)
  7. {
  8. int [] n = new int[10]; /* n 是一个带有 10 个整数的数组 */
  9. int i,j;
  10. /* 初始化数组 n 中的元素 */
  11. for ( i = 0; i < 10; i++ )
  12. {
  13. n[ i ] = i + 100;
  14. }
  15. /* 输出每个数组元素的值 */
  16. for (j = 0; j < 10; j++ )
  17. {
  18. Console.WriteLine("Element[{0}] = {1}", j, n[j]);
  19. }
  20. Console.ReadKey();
  21. }
  22. }
  23. }

foreach遍历数组方法

使用 foreach 循环

在前面的实例中,我们使用一个 for 循环来访问每个数组元素。您也可以使用一个 foreach 语句来遍历数组。

实例

  1. using System;
  2. namespace ArrayApplication
  3. {
  4. class MyArray
  5. {
  6. static void Main(string[] args)
  7. {
  8. int [] n = new int[10]; /* n 是一个带有 10 个整数的数组 */
  9. /* 初始化数组 n 中的元素 */
  10. for ( int i = 0; i < 10; i++ )
  11. {
  12. n[i] = i + 100;
  13. }
  14. /* 输出每个数组元素的值 */
  15. foreach (int j in n ) //int为变量类型 j为变量名 in代表j在数组n里 函数不断地将数组里的数按顺序赋值给j
  16. {
  17. int i = j-100;
  18. Console.WriteLine("Element[{0}] = {1}", i, j);
  19. }
  20. Console.ReadKey();
  21. }
  22. }
  23. }

int为变量类型 j为变量名 in代表j在数组n里 函数不断地将数组里的数按顺序赋值给j
遍历数组:foreach(type objName in collection/Array)
这段语句会逐一检查数组中的所存储的变量值,并且一一将其取出,其中的type是你所要读取的数组对象将要存储在objName变量的数据类型,而objName是定义了一个type类型的变量名,代表每一次从集合和数组(collection/Array)中取得的元素,collection/Array则是所要存取的数组对象。用这种方法只需写一个foreach就可以遍历出除交错数组以外的所有维数的数组。
注:** objName的数据类型type必须与collection/Array对象的类型相同或比它大