C#传递数组参数

在C#中,可以将数组作为参数传递给方法,同时方法可以更改数组元素的值。

一、将一维数组作为参数传递给方法
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Test
{
    class Program
    {
        static void MArray(int[] array)
        {
            for (int i = 0; i < array.Length; i++)
            {
                Console.WriteLine("array[{0}] = {1}", i, array[i]+10);
            }
        }
        static void Main(string[] args)
        {
            // C#将一维数组作为参数传递-www.baike369.com
            int[] arr = new int[] { 1, 2, 3, 4, 5 };
            MArray(arr);                       // 传递数组参数
            Console.WriteLine("-------------");
            MArray(new int[] { 2, 4, 6, 8 });  // 初始化数组并作为参数传递
            Console.ReadLine();
        }
    }
}

运行结果:
 
array[0] = 11
array[1] = 12
array[2] = 13
array[3] = 14
array[4] = 15
-------------
array[0] = 12
array[1] = 14
array[2] = 16
array[3] = 18

二、将二维数组作为参数传递给方法
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace Test
{
    class Program
    {
        static void MArray(int[,] array)
        {
            for (int i = 0; i < 4; i++)
            {
                for (int j = 0; j < 2; j++)
                {
                    Console.WriteLine("array[{0},{1}] = {2}",i,j,array[i,j]+10);
                }
            }
        }
        static void Main(string[] args)
        {
            int[,] arr = new int[,] {{1,2},{3,4,},{5,6},{7,8}};
            MArray(arr);     // 传递二维数组参数
            Console.WriteLine("---------------");
            // 初始化二维数组并作为参数传递
            MArray(new int[,] {{10,20},{30,40,},{50,60},{70,80}});
            Console.ReadLine();
        }
    }
}

运行结果:
 
array[0,0] = 11
array[0,1] = 12
array[1,0] = 13
array[1,1] = 14
array[2,0] = 15
array[2,1] = 16
array[3,0] = 17
array[3,1] = 18
---------------
array[0,0] = 20
array[0,1] = 30
array[1,0] = 40
array[1,1] = 50
array[2,0] = 60
array[2,1] = 70
array[3,0] = 80
array[3,1] = 90

 

posted @ 2015-01-22 14:49  melao2006  阅读(3598)  评论(0编辑  收藏  举报