本節(jié)課向你介紹C#的方法,其目的是:
1.了解方法的結(jié)構(gòu)格式
2.了解靜態(tài)和實(shí)例方法之間的區(qū)別
3.學(xué)會實(shí)例對象的使用
4.學(xué)會如何調(diào)用實(shí)例化的對象
5.學(xué)會方法的四種參數(shù)類型的使用
6.學(xué)會使用"this"引用
以往,對于每個(gè)程序來說,所有的工作都在Main()方法中實(shí)現(xiàn)。這對于功能簡單的程序是合適的,因?yàn)閮H僅用來學(xué)習(xí)一些概念。有個(gè)更好的方法來組織你的程序,那就是使用方法。方法是很有用的,因?yàn)榉椒梢宰屇阍诓煌膯卧蟹珠_設(shè)計(jì)你的邏輯模塊。
方法的結(jié)構(gòu)格式如下:
    
        
            | 屬性 修飾符 返回值類型 方法名(參數(shù)) { 語句 } | 
    
我們將在后面的課程中,討論屬性和修飾符。方法的返回值可以是任何一種C#的數(shù)據(jù)類型,該返回值可以賦給變量,以便在程序的后面部分使用。方法名是唯一,可以被程序調(diào)用。為使得你的代碼變得更容易理解和記憶,方法的取名可以同所要進(jìn)行的操作聯(lián)系起來。你可以傳遞數(shù)據(jù)給方法,也可以從方法中返回?cái)?shù)據(jù)。它們由大括號包圍起來。大括號中的語句實(shí)現(xiàn)了方法的功能。
    
        
            | 1.清單5-1. 一個(gè)簡單的方法: OneMethod.cs | 
    
    
        
            | using System; class OneMethod {
 public static void Main() {
 string myChoice;
 OneMethod om = new OneMethod();
 
 do {
 myChoice = om.getChoice();
 // Make a decision based on the user's choice
 switch(myChoice) {
 case "A":
 case "a":
 Console.WriteLine("You wish to add an address.");
 break;
 case "D":
 case "d":
 Console.WriteLine("You wish to delete an address.");
 break;
 case "M":
 case "m":
 Console.WriteLine("You wish to modify an address.");
 break;
 case "V":
 case "v":
 Console.WriteLine("You wish to view the address list.");
 break;
 case "Q":
 case "q":
 Console.WriteLine("Bye.");
 break;
 default:
 Console.WriteLine("{0} is not a valid choice", myChoice);
 }
 
 // Pause to allow the user to see the results
 Console.Write("Press any key to continue...");
 Console.ReadLine();
 Console.WriteLine();
 } while (myChoice != "Q" && myChoice != "q"); // Keep going until the user wants to quit
 }
 
 string getChoice() {
 string myChoice;
 // Print A Menu
 Console.WriteLine("My Address Book\n");
 Console.WriteLine("A - Add New Address");
 Console.WriteLine("D - Delete Address");
 Console.WriteLine("M - Modify Address");
 Console.WriteLine("V - View Addresses");
 Console.WriteLine("Q - Quit\n");
 Console.WriteLine("Choice (A,D,M,V,or Q): ");
 
 // Retrieve the user's choice
 myChoice = Console.ReadLine();
 return myChoice;
 }
 }
 | 
    
1.清單5-1中的程序類似于第四課中的DoLoop程序。
區(qū)別在于:前一課中的程序打印出菜單內(nèi)容,并在Main()方法中接受用戶的輸入,而本課中,該功能用一個(gè)名為getChoice()的方法實(shí)現(xiàn),該方法的返回值類型是個(gè)字符串類型。在main方法中,在switch語句中用到了該串。方法"getChoice"實(shí)現(xiàn)了調(diào)用時(shí)所完成的工作。方法名后面的括號內(nèi)是空的,因?yàn)檎{(diào)用getChoice()方法時(shí),不需要傳遞任何數(shù)據(jù)。