命名参数

版本新特性 / C# 4.0

using System;

class Program {
    static void DrawBox(int width, int height, bool filled = false,
                        char border = '#') {
        Console.WriteLine(width + "x" + height + " filled=" + filled +
                          " border=" + border);
    }

    static void Main() {
        // *** 以前 ***
        // 过去调用处值的含义要靠顺序猜,或靠注释说明,
        // 而且每个跳过的默认值都得手写出来
        DrawBox(3, 4, false, '*');
        DrawBox(3, 4 /* 高度 */);

        // *** 在 4.0 版本中 ***
        DrawBox(width: 3, height: 4, border: '*');   // filled 保持默认值
        DrawBox(height: 4, width: 3);                // 顺序随意
        DrawBox(3, 4, filled: true);                 // 先位置参数,后命名参数

        // 参数的名称成为契约的一部分:
        // 在库中重命名它,会破坏按名称写出该参数的调用方
    }
}