You can define a method to have 'params' type of argument, with the 'params', you can pass argument as you can do in variable arguments as in C++/C.
Here is one example that shows you some tricks and internals with the params in C#.
class Program
{
static void Main(string[] args)
{
// you can pass an null, the param parameter is null
ParamMethods(null);
// you can pass an empty parameter list, which is like pass a 0-length list
ParamMethods();
// or you can enumerate the list and pass any number of parameters, the compiler
// will generate a list, initialize the param array with the list values.
ParamMethods("Hello3", "world3");
// or you can explicitly pass in an array, and you can do the initialization yourself.
ParamMethods(new [] { "Hello4", "World4"});
}
internal static void ParamMethods(params string[] param)
{
if (param == null)
{
param = new[] { "hello", "world" };
Console.WriteLine("param is null");
return;
}
if (param.Length == 0)
{
param = new[] { "hello2", "world2" };
Console.WriteLine("param.Length == 0");
return;
}
int i = 0;
foreach (var item in param)
{
++i;
Console.WriteLine(i.ToString() + ": " + item);
}
}
}
本文展示C#中使用params关键字处理可变参数的方法及内部实现细节,包括处理空参数、空参数列表、参数初始化和参数传递等技巧。
2143

被折叠的 条评论
为什么被折叠?



