所谓的可选参数就是我们可以在调用方法的时候包含这个参数,也可以省略它。
为表明某个参数是可选的,需要在方法声明的时候为参数提供默认值。
注意事项
1.必选从可选参数列表的最后开始省略,一直到列表开通
2.也就是说,你可以省略最后一个可选参数,或是最后n个可选参数,但是不可以随意选择省略任意可选参数,省略必选从最后开始。
class MyClass
{
/// <summary>
/// int b = 3可选参数
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <returns></returns>
//public int Calc(int a, int b = 3)
//{
// return a + b;
//}
public int Calc(int a = 2, int b = 3, int c = 4)
{
return (a + b) * c;
}
}
class Program
{
static void Main(string[] args)
{
MyClass mc = new MyClass();
//int r0 = mc.Calc(5, 6);//使用显示值
//int r1 = mc.Calc(5);//为b使用默认值
//Console.WriteLine("{0},{1}", r0, r1);
int r0 = mc.Calc(5,6,7);//使用所有的显示值
int r1 = mc.Calc(5,6);//为c使用默认值
int r2 = mc.Calc(5);//为b和c使用默认值
int r3 = mc.Calc();//使用所有的默认值
Console.WriteLine("{0},{1},{2},{3}",r0,r1,r2,r3);
Console.ReadKey();
}
}
为表明某个参数是可选的,需要在方法声明的时候为参数提供默认值。
注意事项
1.必选从可选参数列表的最后开始省略,一直到列表开通
2.也就是说,你可以省略最后一个可选参数,或是最后n个可选参数,但是不可以随意选择省略任意可选参数,省略必选从最后开始。
class MyClass
{
/// <summary>
/// int b = 3可选参数
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <returns></returns>
//public int Calc(int a, int b = 3)
//{
// return a + b;
//}
public int Calc(int a = 2, int b = 3, int c = 4)
{
return (a + b) * c;
}
}
class Program
{
static void Main(string[] args)
{
MyClass mc = new MyClass();
//int r0 = mc.Calc(5, 6);//使用显示值
//int r1 = mc.Calc(5);//为b使用默认值
//Console.WriteLine("{0},{1}", r0, r1);
int r0 = mc.Calc(5,6,7);//使用所有的显示值
int r1 = mc.Calc(5,6);//为c使用默认值
int r2 = mc.Calc(5);//为b和c使用默认值
int r3 = mc.Calc();//使用所有的默认值
Console.WriteLine("{0},{1},{2},{3}",r0,r1,r2,r3);
Console.ReadKey();
}
}