定名实参和可选实参 Named and Optional Arguments
1. 利用“命名实参”,您将能够为特定形参指定实参,方法是将实参与该形参的名称关联,而不是与形参在形参列表中的位置关联。
static void Main(string[] args)
{
Console.WriteLine(CalculateBMI(weight: 123, height: 64)); //实参命名
Console.WriteLine();
}
static int CalculateBMI(int weight,int height)
{
return (weight * 703) / (height * height);
}
有了命名实参,您将不再需要记住或查找形参在所调用方法的形参列表中的顺序。 可以按形参名称指定每个实参的形参。
下面的方法调用都可行:
CalculateBMI(height: 64, weight: 123);
命名实参可以放在位置实参后面,如此处所示。
CalculateBMI(123, height: 64);
但是,位置实参不能放在命名实参后面。 下面的语句会导致编译器错误。
//CalculateBMI(weight: 123, 64);
2. 方法、构造函数、索引器或委托的定义可以指定其形参为必需还是可选。 任何调用都必须为所有必需的形参提供实参,但可以为可选的形参省略实参。
static void Main(string[] args)
{
ExampleClass anExample = new ExampleClass();
anExample.ExampleMethod(1, "One", 1);
anExample.ExampleMethod(2, "Two");
anExample.ExampleMethod(3);
ExampleClass anotherExample = new ExampleClass("Provided name");
anotherExample.ExampleMethod(1, "One", 1);
anotherExample.ExampleMethod(2, "Two");
anotherExample.ExampleMethod(3);
anotherExample.ExampleMethod(4, optionalInt: 4);//运用实参命名,可以跳过之前的可选实参
//anotherExample.ExampleMethod(4, 4) 这样要报错,不能中间默认跳过某几个可选实参,要依次给之前出现的可选实参赋值
}
class ExampleClass
{
private string _name;
public ExampleClass (string name="default name") //构造函数的参数为可选实参
{
_name = name;
}
public void ExampleMethod(int reqired, string optionalstr = "default string", int optionalInt = 10) //第一个为必需实参,后两个为可选实参
{
Console.WriteLine("{0}:{1},{2} and {3}", _name, reqired, optionalstr, optionalInt);
}
}