C# params 可变参数

@果酱  March 28, 2025

params 修饰符

TryParamsCalls();

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

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

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

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

    // 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 };
    ParamsModifierExample(myIntArray);

    object[] myObjArray = { 2, 'b', "test", "again", myIntArray };
    //输出 2 b test again System.Int32[]
    ParamsModifierObjectExample(myObjArray);

    //输出System.Int32[], 因为myIntArray整体作为一对象,参考上面输出
    ParamsModifierObjectExample(myIntArray);

    // The following call causes a compiler error because the object
    // array cannot be converted into an integer array.
    //ParamsModifierExample(myObjArray);    
}
/*
Output:
    1 2 3 4
    1 a test

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

*/

添加新评论