微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

C#中数组参数params关键字的作用

参数数组(params)关键字可以指定在参数数目可变处采用参数的方法参数。

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

先定义一个带有参数数组的方法

public void UseParams(params int[] list)
    {
        for (int i = 0 ; i < list.Length; i++)
        {
            Console.Write(list[i] + " ");
        }
        Console.WriteLine();
    }
可通过以下两个方法调用

① UseParams(1,2,3)

② int[] myarray = new int[3] {10,11,12};
   UseParams(myarray);

using System;
public class MyClass
{

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

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

    static void Main()
    {
        UseParams(1,2,3);
        UseParams2(1,'a',"test");

        // An array of objects can also be passed,as long as
        // the array type matches the method being called.
        int[] myarray = new int[3] {10,12};
        UseParams(myarray);
    }
}

输出
1
2
3

1
a
test

10
11
12

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐