方法参数

C#的方法参数包括:值参数、引用参数、输出参数、参数数组

1)值参数。。。对值参数的修改不会影响到实参。值参数是通过复制实参的值来初始化的。

 static void swap(int a,int b)
        {
            int temp;
            temp = a;
            a = b;
            b = temp;
        }
        static void Main(string[] args)
        {
            int x = 5,y=10;
            Console.WriteLine("x={0},y={1}", x, y);
            swap(x,y);
            Console.WriteLine("x={0},y={1}", x, y);
        }

输出:

x=5,y=10

x=5,y=10

2)引用参数

 static void swap(ref int a,ref int b)
        {
            int temp;
            temp = a;
            a = b;
            b = temp;
        }
        static void Main(string[] args)
        {
            int x = 5,y=10;
            Console.WriteLine("x={0},y={1}", x, y);
            swap(ref x,ref y);
            Console.WriteLine("x={0},y={1}", x, y);
        }

输出:

x=5,y=10

x=10,y=5

注意:使用引用参数时,形参和实参前都必须加上ref关键字,在函数调用前,引用参数必须被初始化。

3)输出参数---用out修饰符修饰的参数。如果希望函数返回多个值,可以用之。。。

ex:

 class Program
    {
        static int Dis(int a,out char b)
        {
            b = (char)a;
            return 0;
        }
        static void Main(string[] args)
        {
            int t = 70, r;
            char m;
            r = Dis(t, out m);
            Console.WriteLine("r={0},m={1}", r, m);
        }
    }

输出:r=0,m=F

注意:使用输出参数时,形参和实参都必须加上out,但是实参在使用前,不必进行初始化。

4)参数数组----用params修饰符修饰,他允许向函数传递个数变化的参数。除了允许在调用中使用可变数量的参数,参数数组与同一类型的值参数完全等效。

ex:

 class Program
    {
        static void Dis(params int[] var)
        {
            for (int i = 0; i < var.Length; i++)
            {
                Console.WriteLine("var[{0}]={1}", i, var[i]);
            }
        }
        static void Main(string[] args)
        {
            int[] arr = { 10, 20, 30 };
            Dis(arr);
            Dis(10, 20);
            Dis();
        }
    }

输出:

注意:参数数组必须是参数中的最后一个参数,一个方法中只能有一个参数数组。params修饰符不能与ref out组合使用

 

posted @ 2013-04-03 23:15  四条眉毛  阅读(276)  评论(0编辑  收藏  举报