C#基础:C#中方法中的四种参数

值参数:

当利用值向方法传递参数时,编译程序给实参的值做一份拷贝,并且将此拷贝传递给该方法,被调用的方法不会修改内存中实参的值,所以使用值参数时,可以保证实际值是安全的,在调用方法时,如果形式化参数的类型是值参数的话,调用的实参的表达式必须保证是正确的值表达式

public class Class1
    {
        static void swapint x,  int y)
        {
            int temp=x;
            x=y;
            y=temp;
        }
        static void Main()
        {
            int i,j;
            i=1;
            j=2;
            swap( i, j);
            Console.WriteLine("i 及 j的值分别为{0},{1}",i,j);
        }
    }

输出结果为1,2

引用型参数:
引用型参数,并不开辟新的内存区域,当利用型参数向方法传递形参时,编译程序将实际值在内存中的地址,传递给方法;在方法中,引用型参数通常已经初始化

public class Class1
    {
        static void swap(ref int x, ref int y)
        {
            int temp=x;
            x=y;
            y=temp;
        }
        static void Main()
        {
            int i,j;
            i=1;
            j=2;
            swap(ref i,ref j);
            Console.WriteLine("i 及 j的值分别为{0},{1}",i,j);
        }
    }

输出结果分别为2,1

输出参数:
当形参为输出参数时,方法调用中的相应参数必须由关键字out,变量在可以作为输出参数传递之前不一定需要明确赋值,但是在将变量作为输出参数传递的调用,out修饰符后应跟随与形参的类型相同的类型声明,在方法返回后,传递的变量被认为经过了初始化

class Program

    {

        static void SplitPath(string path,out string dir,out string name)

        {

            int i = path.Length;

            while (i > 0)

            {

                char ch=path[i-1];

                if(ch=='\\'||ch=='/'||ch==':')

                {

                    break;

                }

                i--;

            }

            dir = path.Substring(0, i);

            name = path.Substring(i);

        }

        static void Main(string[] args)

        {

            string dir, name;

            SplitPath("c:\\windows\\System\\hello.txt", out dir, out name);

            Console.WriteLine(dir);

            Console.WriteLine(name);

            Console.ReadLine();

        }

}

输出结果:

c:\Windows\System\

hello.txt

数组型参数:

以params修饰符声明。params关键字用来声明可变长度的参数列表。方法声明中只能包含一个params参数

如果形参表中包含了数组型参数,那么它必须在参数表中位于最后,另外,参数只允许是一维数组,比如,string[]和string[][]类型都可以作为数组型参数,而string[,]则不能,最后,数组型参数不能再有ref和out修饰符

class Program

    {

        static void F(params int[] args)

        {

            Console.Write("Array contains {0}elements:",args.Length);

            foreach (int i in args)

                Console.Write("{0}",i);

            Console.WriteLine();

        }

        static void Main(string[] args)

        {

            int[] arr = {1,2,3 };

            F(arr);

            F(10,20,30,40);

            F();

            Console.ReadLine();

        }

    }

输出:

Array contains 3 elements: 1 2 3

Array contains 4 elements: 10 20 30 40

Array contains 0 elements:

posted @ 2013-02-19 18:32  乡香田甜  阅读(281)  评论(0编辑  收藏  举报