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);

 

任何调用都必须为所有必需的形参提供实参,但可以为可选的形参省略实参。

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);
}

}

 

相关文章:

  • 2021-10-22
  • 2021-07-06
  • 2021-10-10
  • 2022-12-23
  • 2022-12-23
  • 2021-08-17
猜你喜欢
  • 2022-01-11
  • 2021-11-25
  • 2021-09-16
  • 2022-12-23
  • 2022-12-23
  • 2021-11-23
  • 2021-09-16
相关资源
相似解决方案