.NET Framework 4.0命名参数和可选参数

1.命名参数

class Program
{
    static void Test(int a, int b, int c, int d)
    {
        Console.WriteLine("{0},{1},{2},{3}", a, b, c, d);
    }

    static void Main(string[] args)
    {
        Test(d: 4, c: 3, b: 2, a: 1); //1,2,3,4
        Test(5, 6, c: 7, d: 8); //5,6,7,8
        Console.ReadKey();
    }      
}

注意事项

·调用时命名参数要放在位置参数后面,不然会出错,例如:Test(d: 4, c: 3, 1, 2);

2.可选参数

static void Test(int a = 1, int b =2 , int c = 3, int d = 4)
{
    Console.WriteLine("{0},{1},{2},{3}", a, b, c, d);
}

static void Main(string[] args)
{
    Test(); //1,2,3,4
    Test(5, 6); //5,6,3,4
    Console.ReadKey();
}

注意事项

·声明时可选参数要放在必选参数后面,不然会出错,例如:static void Test(int a = 1, int b =2 , int c = 3, int d);
·调用时为某个可选参数传入实参,则其前面的所有参数都必须传入实参,不然会出错,例如:Test(, 6);

小结

命名参数和可选参数必须一起使用才能显示出优势。若没有可选参数,调用时所有参数必须传值,还不如不用命名参数;若没有命名参数,调用时为某个可选参数传入实参时,其前面所有参数都必须传值,可选参数变得没那么完美。

最后,再看一个例子:

class Program
{
    static void Test(int a = 1, int b =2 , int c = 3, int d = 4)
    {
        Console.WriteLine("{0},{1},{2},{3}", a, b, c, d);
    }

    static void Main(string[] args)
    {
        Test(b: 8); //1,8,3,4
        Console.ReadKey();
    }
}


参数资料

[1].命名实参和可选实参(C# 编程指南):http://msdn.microsoft.com/zh-cn/library/vstudio/dd264739.aspx

评论: 0 | 引用: 0 | 查看次数: 3504
发表评论
登录后再发表评论!