也许你会想到,假如我有一个和可选参数方法不选某个参数相同的方法签名的方法时,C#会怎么处理呢,我们看下下面的代码:
static void DoSomething(int notOpArg, string arg)
{
Console.WriteLine("arg1 = {0}", arg);
{
Console.WriteLine("arg1 = {0}", arg);
}
这里又重载了一个DoSomething这个方法有两个参数,但是没有可选参数,实验证明调用DoSomething(1,”arg”)时会优先执行没有可选参数的方法。
4.方法参数之命名参数
命名参数让我们可以在调用方法时指定参数名字来给参数赋值,这种情况下可以忽略参数的顺序。如下方法声明:
static void DoSomething(int height, int width, string openerName, string scroll)
{
Console.WriteLine("height = {0},width = {1},openerName = {2}, scroll = {3}",height,width,openerName,scroll);
}
{
Console.WriteLine("height = {0},width = {1},openerName = {2}, scroll = {3}",height,width,openerName,scroll);
}
我们可以这样来调用上面声明的方法:
{
DoSomething( scroll : "no",height : 10, width : 5, openerName : "windowname");
Console.ReadLine();
}
DoSomething( scroll : "no",height : 10, width : 5, openerName : "windowname");
Console.ReadLine();
}
很显然的这是一个语法糖,但是在方法参数很多的情况下很有意义,可以增加代码的可读性。