C#学习之--Params关键字的使用

params 关键字可以给一个方法(method)传递数量可变的参数(parameter)

规则

1.params后面的参数类型必须是一维数组,否则会出现编译出错;

2.params后面不允许再有其他参数了,前面可以有;

3.一个方法的申明中只能有一个params关键字

public class MyClass
{
    //UseParams函数在申明的时候 使用了params关键字 后面跟一个int类型的数组
    public static void UseParams(params int[] list)
    {
        for (int i = 0; i < list.Length; i++)
        {
            Console.Write(list[i] + " ");
        }
        Console.WriteLine();
    }

    //UseParams2函数在申明的时候 使用了params关键字 后面跟一个object类型的数组
    //由于是object类型,实际里面可以传int string 等各种参数的组合
    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);//调用方式1,用逗号分隔的一串参数,int[]
        UseParams2(1, 'a', "test");//调用方式1,用逗号分隔的一串参数,object[]

        // A params parameter accepts zero or more arguments.
        // The following calling statement displays only a blank line.
        UseParams2();//调用方式3,不传参数/空参数 输出空白

        // 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);//调用方式2,先申明int[]数组再传

        object[] myObjArray = { 2, 'b', "test", "again" };
        UseParams2(myObjArray);//调用方式2,先申明object[]数组再传

        //object[]无法转换成int[] 下面的语句会编译出错
        // The following call causes a compiler error because the object
        // array cannot be converted into an integer array.
        UseParams(myObjArray);

        //int[] 整体作为object[]的第一个元素,Console.Write输出的是System.Int32[]
        // 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[]
*/
View Code

上述代码转载自链接:https://zhuanlan.zhihu.com/p/409478413

 

posted @ 2021-09-12 22:37  HelloWorld庄先生  阅读(210)  评论(0编辑  收藏  举报