深入解析C#中的命名實(shí)參和可選實(shí)參
Visual C# 2010 引入了命名實(shí)參和可選實(shí)參。利用“命名實(shí)參”,您將能夠?yàn)樘囟ㄐ螀⒅付▽?shí)參,方法是將實(shí)參與該形參的名稱關(guān)聯(lián),而不是與形參在形參列表中的位置關(guān)聯(lián)。利用“可選實(shí)參”,您將能夠?yàn)槟承┬螀⑹÷詫?shí)參。這兩種技術(shù)都可與方法、索引器、構(gòu)造函數(shù)和委托一起使用。
在使用命名實(shí)參和可選實(shí)參時(shí),將按實(shí)參出現(xiàn)在實(shí)參列表(而不是形參列表)中的順序計(jì)算這些實(shí)參。
命名形參和可選形參一起使用時(shí),您將能夠只為可選形參列表中的少數(shù)形參提供實(shí)參。此功能大大方便了對(duì) COM 接口(例如 Microsoft Office 自動(dòng)化 API)的調(diào)用。
命名實(shí)參
有了命名實(shí)參,您將不再需要記住或查找形參在所調(diào)用方法的形參列表中的順序??梢园葱螀⒚Q指定每個(gè)實(shí)參的形參。例如,可以采用標(biāo)準(zhǔn)方式調(diào)用計(jì)算身體質(zhì)量指數(shù) (BMI) 的函數(shù),方法是依照該函數(shù)定義的順序按位置發(fā)送體重和身高的實(shí)參。
CalculateBMI(123, 64);
如果不記得形參的順序,但卻知道其名稱,您可以按任意順序(先發(fā)送體重或先發(fā)送身高)發(fā)送實(shí)參。
CalculateBMI(weight: 123, height: 64); CalculateBMI(height: 64, weight: 123);
命名實(shí)參還可以標(biāo)識(shí)每個(gè)實(shí)參所表示的含義,從而改進(jìn)代碼的可讀性。
命名實(shí)參可以放在位置實(shí)參后面,如此處所示。
CalculateBMI(123, height: 64);
但是,位置實(shí)參不能放在命名實(shí)參后面。下面的語(yǔ)句會(huì)導(dǎo)致編譯器錯(cuò)誤。
CalculateBMI(weight: 123, 64);
示例
下面的代碼實(shí)現(xiàn)本節(jié)中的示例。
class NamedExample { static void Main(string[] args) { // The method can be called in the normal way, by using positional arguments. Console.WriteLine(CalculateBMI(123, 64)); // Named arguments can be supplied for the parameters in either order. Console.WriteLine(CalculateBMI(weight: 123, height: 64)); Console.WriteLine(CalculateBMI(height: 64, weight: 123)); // Positional arguments cannot follow named arguments. // The following statement causes a compiler error. //Console.WriteLine(CalculateBMI(weight: 123, 64)); // Named arguments can follow positional arguments. Console.WriteLine(CalculateBMI(123, height: 64)); } static int CalculateBMI(int weight, int height) { return (weight * 703) / (height * height); } }
可選參數(shù)
方法、構(gòu)造函數(shù)、索引器或委托的定義可以指定其形參為必需還是可選。任何調(diào)用都必須為所有必需的形參提供實(shí)參,但可以為可選的形參省略實(shí)參。
每個(gè)可選形參都具有默認(rèn)值作為其定義的一部分。如果沒(méi)有為該形參發(fā)送實(shí)參,則使用默認(rèn)值。默認(rèn)值必須是一個(gè)表達(dá)式的以下類(lèi)型之一:
常數(shù)表達(dá)式;
窗體 new ValType()的表達(dá)式, ValType 是值類(lèi)型,例如 枚舉 或 結(jié)構(gòu);
窗體 默認(rèn) (ValType)的表達(dá)式, ValType 是值類(lèi)型。
可選形參在形參列表的末尾定義,位于任何必需的形參之后。如果調(diào)用方為一系列可選形參中的任意一個(gè)形參提供了實(shí)參,則它必須為前面的所有可選形參提供實(shí)參。實(shí)參列表中不支持使用逗號(hào)分隔的間隔。例如,在以下代碼中,使用一個(gè)必選形參和兩個(gè)可選形參定義實(shí)例方法 ExampleMethod。
public void ExampleMethod(int required, string optionalstr = "default string", int optionalint = 10)
下面對(duì) ExampleMethod 的調(diào)用導(dǎo)致編譯器錯(cuò)誤,原因是為第三個(gè)形參而不是為第二個(gè)形參提供了實(shí)參。
anExample.ExampleMethod(3, ,4);
但是,如果您知道第三個(gè)形參的名稱,則可以使用命名實(shí)參來(lái)完成任務(wù)。
anExample.ExampleMethod(3, optionalint: 4);
IntelliSense 使用括號(hào)指示可選形參,如下圖所示。
示例
在下面的示例中,ExampleClass 的構(gòu)造函數(shù)具有一個(gè)形參,該形參是可選的。實(shí)例方法 ExampleMethod 具有一個(gè)必需的形參:required,以及兩個(gè)可選形參:optionalstr 和 optionalint。 Main 中的代碼演示了可用于調(diào)用構(gòu)造函數(shù)和方法的不同方式。
namespace OptionalNamespace { class OptionalExample { static void Main(string[] args) { // Instance anExample does not send an argument for the constructor's // optional parameter. ExampleClass anExample = new ExampleClass(); anExample.ExampleMethod(1, "One", 1); anExample.ExampleMethod(2, "Two"); anExample.ExampleMethod(3); // Instance anotherExample sends an argument for the constructor's // optional parameter. ExampleClass anotherExample = new ExampleClass("Provided name"); anotherExample.ExampleMethod(1, "One", 1); anotherExample.ExampleMethod(2, "Two"); anotherExample.ExampleMethod(3); // The following statements produce compiler errors. // An argument must be supplied for the first parameter, and it // must be an integer. //anExample.ExampleMethod("One", 1); //anExample.ExampleMethod(); // You cannot leave a gap in the provided arguments. //anExample.ExampleMethod(3, ,4); //anExample.ExampleMethod(3, 4); // You can use a named parameter to make the previous // statement work. anExample.ExampleMethod(3, optionalint: 4); } } class ExampleClass { private string _name; // Because the parameter for the constructor, name, has a default // value assigned to it, it is optional. public ExampleClass(string name = "Default name") { _name = name; } // The first parameter, required, has no default value assigned // to it. Therefore, it is not optional. Both optionalstr and // optionalint have default values assigned to them. They are optional. public void ExampleMethod(int required, string optionalstr = "default string", int optionalint = 10) { Console.WriteLine("{0}: {1}, {2}, and {3}.", _name, required, optionalstr, optionalint); } } }
輸出:
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 接口
命名實(shí)參和可選實(shí)參,以及對(duì)動(dòng)態(tài)對(duì)象的支持和其他增強(qiáng)功能大大提高了與 COM API(例如 Office 自動(dòng)化 API)的互操作性。
例如,Microsoft Office Excel 的 Range 接口中的 AutoFormat 方法具有七個(gè)形參,這七個(gè)形參都是可選的。這些形參如下圖所示。
在 C# 3.0 和早期版本中,每個(gè)形參都需要一個(gè)實(shí)參,如以下示例所示。
// 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);
但是,可以通過(guò)使用 C# 4.0 中引入的命名實(shí)參和可選實(shí)參來(lái)大大簡(jiǎn)化對(duì) AutoFormat 的調(diào)用。如果不希望更改形參的默認(rèn)值,則可以通過(guò)使用命名實(shí)參和可選實(shí)參來(lái)為可選形參省略實(shí)參。在下面的調(diào)用中,僅為七個(gè)形參中的其中一個(gè)指定了值。
// 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 );
重載決策
使用命名實(shí)參和可選實(shí)參將在以下方面對(duì)重載決策產(chǎn)生影響:
如果方法、索引器或構(gòu)造函數(shù)的各個(gè)形參均為可選,或者按名稱或位置與調(diào)用語(yǔ)句中的單個(gè)實(shí)參對(duì)應(yīng),并且該實(shí)參可轉(zhuǎn)換為形參的類(lèi)型,則該方法、索引器或構(gòu)造函數(shù)是執(zhí)行的候選項(xiàng)。
如果找到多個(gè)候選項(xiàng),則會(huì)將首選轉(zhuǎn)換的重載決策規(guī)則應(yīng)用于顯式指定的實(shí)參。將忽略可選形參已省略的實(shí)參。
如果兩個(gè)候選項(xiàng)不相上下,則會(huì)將沒(méi)有可選形參的候選項(xiàng)作為首選項(xiàng),對(duì)于這些可選形參,已在調(diào)用中為其省略了實(shí)參。這是具有較少形參的候選項(xiàng)的重載決策中一般首選項(xiàng)的結(jié)果。
上一篇:淺談C#中簡(jiǎn)單的異常引發(fā)與處理操作
欄 目:C#教程
下一篇:簡(jiǎn)單學(xué)習(xí)C#中的泛型方法使用
本文標(biāo)題:深入解析C#中的命名實(shí)參和可選實(shí)參
本文地址:http://mengdiqiu.com.cn/a1/C_jiaocheng/6715.html
您可能感興趣的文章
- 01-10深入淺出23種設(shè)計(jì)模式
- 01-10C#中查找Dictionary中的重復(fù)值的方法
- 01-10C#將圖片存放到SQL SERVER數(shù)據(jù)庫(kù)中的方法
- 01-10關(guān)于nancy中的身份驗(yàn)證
- 01-10C#中的事務(wù)用法實(shí)例分析
- 01-10C#實(shí)現(xiàn)讀取DataSet數(shù)據(jù)并顯示在ListView控件中的方法
- 01-10C#中的正則表達(dá)式介紹
- 01-10C#開(kāi)發(fā)中的垃圾回收機(jī)制簡(jiǎn)析
- 01-10C#語(yǔ)言中的修飾符匯總
- 01-10C#中的 == 和equals()區(qū)別淺析


閱讀排行
- 1C語(yǔ)言 while語(yǔ)句的用法詳解
- 2java 實(shí)現(xiàn)簡(jiǎn)單圣誕樹(shù)的示例代碼(圣誕
- 3利用C語(yǔ)言實(shí)現(xiàn)“百馬百擔(dān)”問(wèn)題方法
- 4C語(yǔ)言中計(jì)算正弦的相關(guān)函數(shù)總結(jié)
- 5c語(yǔ)言計(jì)算三角形面積代碼
- 6什么是 WSH(腳本宿主)的詳細(xì)解釋
- 7C++ 中隨機(jī)函數(shù)random函數(shù)的使用方法
- 8正則表達(dá)式匹配各種特殊字符
- 9C語(yǔ)言十進(jìn)制轉(zhuǎn)二進(jìn)制代碼實(shí)例
- 10C語(yǔ)言查找數(shù)組里數(shù)字重復(fù)次數(shù)的方法
本欄相關(guān)
- 01-10C#通過(guò)反射獲取當(dāng)前工程中所有窗體并
- 01-10關(guān)于ASP網(wǎng)頁(yè)無(wú)法打開(kāi)的解決方案
- 01-10WinForm限制窗體不能移到屏幕外的方法
- 01-10WinForm繪制圓角的方法
- 01-10C#實(shí)現(xiàn)txt定位指定行完整實(shí)例
- 01-10WinForm實(shí)現(xiàn)仿視頻 器左下角滾動(dòng)新
- 01-10C#停止線程的方法
- 01-10C#實(shí)現(xiàn)清空回收站的方法
- 01-10C#通過(guò)重寫(xiě)Panel改變邊框顏色與寬度的
- 01-10C#實(shí)現(xiàn)讀取注冊(cè)表監(jiān)控當(dāng)前操作系統(tǒng)已
隨機(jī)閱讀
- 01-10delphi制作wav文件的方法
- 01-11ajax實(shí)現(xiàn)頁(yè)面的局部加載
- 01-10C#中split用法實(shí)例總結(jié)
- 04-02jquery與jsp,用jquery
- 08-05DEDE織夢(mèng)data目錄下的sessions文件夾有什
- 01-10SublimeText編譯C開(kāi)發(fā)環(huán)境設(shè)置
- 01-11Mac OSX 打開(kāi)原生自帶讀寫(xiě)NTFS功能(圖文
- 01-10使用C語(yǔ)言求解撲克牌的順子及n個(gè)骰子
- 08-05dedecms(織夢(mèng))副欄目數(shù)量限制代碼修改
- 08-05織夢(mèng)dedecms什么時(shí)候用欄目交叉功能?