可选参数

版本新特性 / C# 4.0

using System;

class Program {
    // *** 以前 ***
    // 过去为了默认值要写一族重载,每个都转发到下一个,
    // 每新增一个参数,这一族就翻一倍
    static string ReportOld(string title) { return ReportOld(title, 10); }
    static string ReportOld(string title, int width) { return ReportOld(title,
                          width, '.'); }
    static string ReportOld(string title, int width, char fill) {
        return title.PadRight(width, fill);
    }

    // *** 在 4.0 版本中 ***
    static string Report(string title, int width = 10, char fill = '.') {
        return title.PadRight(width, fill);
    }

    static void Main() {
        Console.WriteLine(ReportOld("total"));
        Console.WriteLine(Report("total"));
        Console.WriteLine(Report("total", 15));
        Console.WriteLine(Report("total", 15, '-'));

        // 默认值必须是常量,编译器会把它直接写进调用里:
        // 在库中修改默认值,只有调用方重新编译后才会生效
    }
}