C#关键字—方法参数

Printed From Microsoft.docs;

使用 params 关键字可以指定采用数目可变的参数的方法参数

可以发送参数声明中所指定类型的逗号分隔的参数列表或指定类型的参数数组。 还可以不发送参数。 如果未发送任何参数,则 params 列表的长度为零。

在方法声明中的 params 关键字之后不允许有任何其他参数,并且在方法声明中只允许有一个 params 关键字。

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[]
*/
namespace _050_参数数组__定义一个参数个数不确定的函数_ {
    class Program {
        static int Sum(int[] array)//如果一个函数定义了参数,那么在调用这个函数的时候,一定要传递对应类型的参数,否则无法调用(编译器编译不通过)
        {
            int sum = 0;
            for (int i = 0; i < array.Length; i++)
            {
                sum += array[i];
            }
            return sum;
        }

        static int Plus(params int[] array)//这里定义了一个int类型的参数数组,参数数组和数组参数(上面的)的不同,在于函数的调用,调用参数数组的函数的时候,我们可以传递过来任意多个参数,然后编译器会帮我们自动组拼成一个数组,参数如果是上面的数组参数,那么这个数组我们自己去手动创建
        {
            int sum = 0;
            for (int i = 0; i < array.Length; i++) {
                sum += array[i];
            }
            return sum;
        }
        static void Main(string[] args)
        {
            int sum = Sum(new int[] {23, 4, 34, 32, 32, 42, 4});
            Console.WriteLine(sum);
            int sum2 = Plus(23, 4, 5, 5, 5, 32, 423, 42, 43,23,42,3);//参数数组就是帮我们 减少了一个创建数组的过程 
            Console.WriteLine(sum2);
            Console.ReadKey();
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/bananana/p/8985703.html