C#方法参数关键字

一、params关键字

prams告诉函数的调用者,该函数的参数数量是可变,如果调用函数的参数标识了params关键字,那么我们可以使用逗号分割的参数或者一个数组来作为参数:

1.这里只能是数组,List等集合是不可以的

2.params标识的参数必须是函数的最后一个参数,因此能一个函数也只能有一个带params标识的参数。

来自MSDN代码示例:

 

public class MyClass
{
    public static void UseParams(params int[] list)
    {
        for (int i = 0; i < list.Length; i++)
        {
            Console.Write(list[i] + " ");
        }
        Console.WriteLine();
    }

    public static void UseParams2(params object[] list)
    {
        for (int i = 0; i < list.Length; i++)
        {
            Console.Write(list[i] + " ");
        }
        Console.WriteLine();
    }

    static void Main()
    {
        // You can send a comma-separated list of arguments of the  
        // specified type.
        UseParams(1, 2, 3, 4);
        UseParams2(1, 'a', "test");

        // A params parameter accepts zero or more arguments. 
        // The following calling statement displays only a blank line.
        UseParams2();

        // An array argument can be passed, as long as the array 
        // type matches the parameter type of the method being called. 
        int[] myIntArray = { 5, 6, 7, 8, 9 };
        UseParams(myIntArray);

        object[] myObjArray = { 2, 'b', "test", "again" };
        UseParams2(myObjArray);

        // The following call causes a compiler error because the object 
        // array cannot be converted into an integer array. 
        //UseParams(myObjArray); 

        // The following call does not cause an error, but the entire  
        // integer array becomes the first element of the params array.
        UseParams2(myIntArray);
    }
}
/*
Output:
    1 2 3 4
    1 a test

    5 6 7 8 9
    2 b test again
    System.Int32[]
*/

 

二、ref/out关键字

将ref/out放在一起,是因为ref和out很相似,它们都允许函数参数在函数执行过程中被修改并可以在函数外得到修改后的数据,应该对照来理解:

1.out关键字在调用前可以不初始化,而在函数调用中,必须为out赋值,值只可以传出;ref在调用前必须有值,调用函数可以读取或者改变他的值,值可以传入同时传出;

 

        public void TestRef(ref int value)
        { 
           //code
        }

 

        int val;
        //使用了未赋值的局部变量val
        TestRef(ref val);

 

2.out关键字是为了获得除了返回值以外的额外输出;ref参数是为了修饰那些可能被修改的参数

 

        public void TestOut(out string outParam)
        {
            //使用了未赋值的out参数outParam
            outParam = outParam + "asdfd";
        }

 

 

 

 

 

posted @ 2013-12-12 21:33  Skysper  阅读(1433)  评论(0编辑  收藏  举报