输出:
Default name: 1, One, and 1.
Default name: 2, Two, and 10.
Default name: 3, default string, and 10.
Provided name: 1, One, and 1.
Provided name: 2, Two, and 10.
Provided name: 3, default string, and 10.
Default name: 3, default string, and 4.
COM 接口
命名实参和可选实参,以及对动态对象的支持和其他增强功能大大提高了与 COM API(例如 Office 自动化 API)的互操作性。
例如,Microsoft Office Excel 的 Range 接口中的 AutoFormat 方法具有七个形参,这七个形参都是可选的。这些形参如下图所示。
在 C# 3.0 和早期版本中,每个形参都需要一个实参,如以下示例所示。
// In C# 3.0 and earlier versions, you need to supply an argument for
// every parameter. The following call specifies a value for the first
// parameter, and sends a placeholder value for the other six. The
// default values are used for those parameters.
var excelApp = new Microsoft.Office.Interop.Excel.Application();
excelApp.Workbooks.Add();
excelApp.Visible = true;
var myFormat =
Microsoft.Office.Interop.Excel.XlRangeAutoFormat.xlRangeAutoFormatAccounting1;
excelApp.get_Range("A1", "B4").AutoFormat(myFormat, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
但是,可以通过使用 C# 4.0 中引入的命名实参和可选实参来大大简化对 AutoFormat 的调用。如果不希望更改形参的默认值,则可以通过使用命名实参和可选实参来为可选形参省略实参。在下面的调用中,仅为七个形参中的其中一个指定了值。
// The following code shows the same call to AutoFormat in C# 4.0. Only
// the argument for which you want to provide a specific value is listed.
excelApp.Range["A1", "B4"].AutoFormat( Format: myFormat );
重载决策
使用命名实参和可选实参将在以下方面对重载决策产生影响:
如果方法、索引器或构造函数的各个形参均为可选,或者按名称或位置与调用语句中的单个实参对应,并且该实参可转换为形参的类型,则该方法、索引器或构造函数是执行的候选项。
如果找到多个候选项,则会将首选转换的重载决策规则应用于显式指定的实参。将忽略可选形参已省略的实参。











