多載限制在參數列,也就是參數版本的不同,這是說參數的型態或數量不同,才構成不同的參數版本,若只有回傳值型態不同,則無法通過編譯。
舉例如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | class Demo { void DoSomething( int i) { System.Console.WriteLine( "There is no spoon." ); } void DoSomething( string s) { System.Console.WriteLine(s); } string DoSomething( int i, string s) { return s; } static void Main() { Demo d = new Demo(); d.DoSomething(1); d.DoSomething( "Free your mind." ); System.Console.WriteLine(d.DoSomething(2, "Pardon?" )); } } /* 《程式語言教學誌》的範例程式 檔名:class31.cs 功能:示範 C# 程式 作者:張凱慶 時間:西元 2013 年 6 月 */ |
此例 Demo 有 3 個參數版本的 DoSomething() ,分別需要一個 int 、一個 string 及 int 與 string 各一個
2 3 4 5 6 7 8 9 10 11 12 | void DoSomething( int i) { System.Console.WriteLine( "There is no spoon." ); } void DoSomething( string s) { System.Console.WriteLine(s); } string DoSomething( int i, string s) { return s; } |
編譯執行,結果如下

中英文術語對照 | |
---|---|
類別 | class |
方法 | method |
多載 | overloading |
您可以繼續參考
類別
相關目錄
回 C# 快速導覽
回 C# 教材
回首頁
參考資料
Standard ECMA-334 C# Language Specification
msdn: 7.4.2 多載解析
沒有留言:
張貼留言