您的位置:首页 > 编程语言 > C#

C#中如何解决参数个数可变的问题

2013-08-01 23:30 218 查看
       首先我们需要了解一个关键字叫  params  。

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

   msdn上的示例:

// cs_params.cs
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息