天天看点

方法参数关键字params、ref及out

这是三个关键字通过字面不是很好理解,我通过三个demo 分别表示一下。

Params :

     public static void UseParams (params object [] list)

        {

            for (int i = 0; i < list.Length; i++)

            {

                Console .WriteLine(list[i]);

            }

        }

        static void Main(string [] args)

        {

            UseParams ('a' , "aa" ,"3" );

            UseParams ('b' , "shit" );

            UseParams ("ok" );

            Console .Read();

        }

通过上面的Demo 可以总结出Params 在方法的参数数目可变的时候使用,需要注意的是在方法声明中使用params 关键字之后不允许再有任何其他参数,并且方法声明中只允许有一个params 关键字;

Ref :

         public static void UseRef(ref int i)

        {

            i += 100;

            Console .WriteLine("i = {0}" , i);

        }

        static void Main(string [] args)

        {

            int i = 10;

            Console .WriteLine("Before the method calling: i = {0}" , i);

            UseRef(ref i);

            Console .WriteLine("After the method calling: i = {0}" , i);

            Console .Read();

        }

        // 控制台输出:

        //Before the method calling : i = 10

        //i = 110

        //After the method calling: i = 110

通过这个Demo 发现使用ref 关键字,使参数按引用传递,其效果是,当控制权传递回调用方法时,在方法中对参数所做的任何更改都将反映在该变量中。

说明:

1 、若要使用 ref 参数,则方法定义和调用方法都必须显式使用 ref 关键字。

2 、传递到 ref 参数的参数必须最先初始化。这与 out 不同,out 的参数在传递之前不需要显式初始化。

3 、属性不是变量,因此不能作为 ref 参数传递。

4 、尽管 ref 和 out 在运行时的处理方式不同,但它们在编译时的处理方式是相同的。因此,如果一个方法采用 ref 参数,而另一个方法采用 out 参数,则无法重载这两个方法。例如,从编译的角度来看,以下代码中的两个方法是完全相同的。如果尝试这么做,将导致不能编译该代码。

5 、如果一个方法采用 ref 或 out 参数,而另一个方法不采用这两类参数,则可以进行重载。

Out :

public static void UseOut(out int i)

        {

            i = 10;

            i += 100;

            Console .WriteLine("i = {0}" , i);

        }

        static void Main(string [] args)

        {

            int i;

            UseOut(out i);

            Console .WriteLine("After the method calling: i = {0}" , i);

            Console .Read();

        }

通过上面发现out 与ref 十分相似,不同之处在于:

        1 、ref 要求变量必须在传递之前进行初始化。

2 、尽管作为 out 参数传递的变量不需要在传递之前进行初始化,但需要调用方法以便在方法返回之前赋值。