您当前的位置: 首页 >  ar

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

发布时间:2010-11-22 15:10:00 ,浏览量:0

参数数组(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,11,12};         UseParams(myarray);     } }

输出 1 2 3

1 a test

10 11 12

关注
打赏
1688896170
查看更多评论

暂无认证

  • 0浏览

    0关注

    106170博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文
立即登录/注册

微信扫码登录

0.1063s