1.可选实参要求:
(1):可选参数必须位于必选实参之后。
(2):可选参数的默认值必须为常量,如数字,常量字符串,null,const,成员,枚举成员。
(3):参数数组不能为可选参数(params int [] intput = null)
(4):用ref或者out关键字标识的参数不能设置为可选参数
案列:
static void Main(string[] args)
{
UseOptArgs u = new UseOptArgs();
u.Display("this is a str");
u.Display("this is a str", 10);
u.Display("this is a str",5,12);
}
class UseOptArgs
{
public void Display(string str , int start=0,int stop=-1)
{
if (stop < 0)
{
stop = str.Length;
}
if (stop > str.Length | start > stop | start < 0)
{
return;
}
for (int i = start; i < stop; i++)
{
Console.Write(str[i]);
}
Console.WriteLine();
}
}
结果: