C# 参数
C# 参数
在 C# 中,params 是一个关键字,用于指定带有可变数量参数的参数。当我们不知道先验参数的数量时,它很有用。在函数声明中,只允许一个 params 关键字,并且不允许在 params 关键字之后附加参数。
C# 参数示例 1
using System;
namespace AccessSpecifiers
{
class Program
{
// User defined function
public void Show(params int[] val) // Params Paramater
{
for (int i=0; i<val.Length; i++)
{
Console.WriteLine(val[i]);
}
}
// Main function, execution entry point of the program
static void Main(string[] args)
{
Program program = new Program(); // Creating Object
program.Show(2,4,6,8,10,12,14); // Passing arguments of variable length
}
}
}
输出:
C# 参数示例 2
在此示例中,我们使用允许输入任意数量的任意类型输入的对象类型参数。
using System;
namespace AccessSpecifiers
{
class Program
{
// User defined function
public void Show(params object[] items) // Params Paramater
{
for (int i = 0; i < items.Length; i++)
{
Console.WriteLine(items[i]);
}
}
// Main function, execution entry point of the program
static void Main(string[] args)
{
Program program = new Program(); // Creating Object
program.Show("Ramakrishnan Ayyer","Ramesh",101, 20.50,"Peter", 'A'); // Passing arguments of variable length
}
}
}
输出:
Ramakrishnan Ayyer
Ramesh
101
20.5
Peter
A