C#方法構建的簡單介紹


到這里,我們學習了C#一些常見的,重要的基本元素,目前已經夠用了,在以后的學習中我們在逐漸往里添加。在前幾節的

學習中,我們稍微的滲透了一些方法的相關信息,那么現在我們着重介紹一下方法。

C#方法也叫函數,我們可以繼續用類比的方式去理解方法,相信有過工控經驗的童鞋們,肯定直到FB,FC塊的概念吧,

其實C#也一樣,也類似與我們的靜態方法和非靜態方法,也需要我們對其形參進行實例化。他們的產生或者作用和PLC一樣

也是一種重用機制。

方法

概念:方法表示這個對象能夠做什么,也就是封裝了這個對象的行為。

類型:實例方法→靜態方法→(抽象方法,虛方法)→特殊的:構造方法(對象創建的時候使用)

語法:

[public] static 返回值類型 方法名([參數列表])

{

    //這里編寫方法的主體(功能實現的具體過程)

    方法體;

    return 返回值;//如果沒有返回值,則不需要寫該語句

}

調用規范:對象名.方法名(參數1,參數2,。。。) 靜態方法

方法名定義:一般是“動詞”或者“動賓短語”,采用Pascal命名法,首字母大寫,不能已數字開頭。

 

public:訪問修飾符,公開公共的,那都可以訪問。

static:靜態的

返回值類型:如果不需要返回值,寫void

參數列表:完成這個方法所必須要提供給這個方法的條件。如果沒有參數,()也不能省略。

return的作用:1.在方法中返回要返回的值。

              2.立即結束本次方法。

方法寫好后,一定要在Main中調用,是不是和PLC很像呢。

語法:類名.方法名([參數])

如果你寫的方法和Main函數同在一個program中類名可以省略。

如果被調用者想要得到調用者的值:

1)傳遞參數。

2)使用靜態字段來模擬全局變量。

如果調用者想要得到被調用者的值

1)返回值

無論實參還是形參,都是在內存那種開辟了空間了。

我們在構建方法時,一定要使方法單一化。方法中最忌諱的就是出現提示用戶的字眼。

我們看一個練習:讀取輸入的整數,定義成方法,如果用戶輸入的是數字則返回,否則重新輸入。

 

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace 草稿
 8 {
 9     class Program
10     {
11         static void Main(string[] args)
12         {
13             Console.WriteLine("請輸入一個數字");
14             string input = Console.ReadLine();
15             int number = GetNumber(input);
16             Console.WriteLine(number);
17             Console.ReadKey();
18         }
19 
20         public static int GetNumber(string s)
21         {
22             while (true)
23             {
24                 try
25                 {
26                     int number = Convert.ToInt32(s);
27                     return number;
28                 }
29                 catch 
30                 {
31 
32                     Console.WriteLine("請重新輸入");
33                     s = Console.ReadLine();
34                 }
35             }
36         }
37     }
38 }

 

其實綜合前幾個章節的講述,我不難發現死循環不是一無是處的,有時候在循環問答的時候還是很有幫助的。

我們繼續夯實一下:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace 草稿
 8 {
 9     class Program
10     {
11         static void Main(string[] args)
12         {
13             Console.WriteLine("請輸入yes或者no");
14             string str = Console.ReadLine();
15             string answer = IsYesOrNo(str);
16             Console.ReadKey();
17         }
18 
19         public static string IsYesOrNo(string input)
20         {
21             while (true)
22             {
23                 if (input == "yes" || input == "no")
24                 {
25                     return input;
26                 }
27                 else
28                 {
29                     Console.WriteLine("只能輸入yes或者no,請重新輸入");
30                 }
31                
32             }
33         }
34     }
35 }

下面我們在研究一下關於方法的三個高級參數:

(1)out參數

如果在同一個方法中,返回多個同類型的的值的時候,可以考慮返回一個數組,但是,如果返回多個不同類型的值的時候,

返回數組就不行了,那么這個時候我們可以考慮out參數。

out參數就側重於在一個方法中可以返回多個不同類型的值。(當然也可以是多個相同值)

 

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace 草稿
 8 {
 9     class Program
10     {
11         static void Main(string[] args)
12         {
13             int[] numbers = { 1,2,3,4,5,6,7,8,9,0};
14             int max = 0;
15             int min = 0;
16             int sum = 0;
17             int avg = 0;
18 
19             Test(numbers,out max,out min,out sum,out avg);
20             Console.WriteLine(max);
21             Console.WriteLine(min);
22             Console.WriteLine(sum);
23             Console.WriteLine(avg);
24             Console.ReadKey();
25         }
26 
27         public static void Test(int[] nums,out int max,out int min,out int sum,out int avg)
28         {
29             max = nums[0];
30             min = nums[0];
31             sum = 0;
32             for (int i = 0; i < nums.Length; i++)
33             {
34                 if (nums[i] > max)
35                 {
36                     max = nums[i];
37                 }
38                 if (nums[i] < min)
39                 {
40                     min = nums[i];
41                 }
42                 sum += nums[i];
43             }
44             avg = sum / nums.Length;
45         }
46     }
47 }

 

練習:提示用戶輸入用戶名和密碼,寫一個方法判斷用戶輸入是否正確。返回用戶一個登陸結果和一個登錄信息。

      如果用戶名錯誤,除了返回登陸結果之外,還要返回一個“登錄錯誤”。密碼錯誤,返回“密碼錯誤”。

 

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace 草稿
 8 {
 9     class Program
10     {
11         static void Main(string[] args)
12         {
13             Console.WriteLine("請輸入用戶名");
14             string userName = Console.ReadLine();
15             Console.WriteLine("請輸入密碼");
16             string userPwd = Console.ReadLine();
17             string msg;
18             bool b = IsLogin(userName,userPwd,out msg);
19             Console.WriteLine(b);
20             Console.WriteLine(msg);
21             Console.ReadKey();
22         }
23 
24         public static bool IsLogin(string name,string pwd,out string msg)
25         {
26             if (name == "admin" && pwd == "888888")
27             {
28                 msg = "登錄成功";
29                 return true;
30             }
31             else if (name == "admin")
32             {
33                 msg = "密碼錯誤";
34                 return false;
35             }
36             else if (pwd == "888888")
37             {
38                 msg = "用戶名錯誤";
39                 return false;
40             }
41             else
42             {
43                 msg = "未知錯誤";
44                 return false;
45             }
46         }
47     }
48 }

 我們發現我們再用out參數的時候,一定要在方法內部賦值。因為值是從方法內部傳出去的。

(2)ref參數

 

能夠將一個變量帶入一個方法中進行改變,改變完成后,再將改變后的值帶出方法。(非常類似與return),而且需要從方法的外部賦值。

ref的作用就是將參數帶入到方法內部,再把值帶出。所以ref參數要求方法外必須賦值,而方法內可以不賦值。

(3)params可變參數

將實參列表中跟可變參數數組類型一致的元素都當作數組的元素去處理。必須是形參列表中最后一個參數。

 

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace Panel
 8 {
 9     class Program
10     {
11         static void Main(string[] args)
12         {
13             Test("張三",99,88,77);
14 
15             Console.ReadKey();
16         }
17 
18         public static void Test(string name,params int[] score)
19         {
20             int sum = 0;
21             for (int i = 0; i < score.Length; i++)
22             {
23                 sum += score[i];
24             }
25 
26             Console.WriteLine("{0}這次考試的總成績是{1}",name,sum);
27         }
28     }
29 }

 


方法的重載

方法重載的好處

1.減少類的對外接口(只顯示一個方法),降低類的復雜度。

2.便於用戶使用(相同功能的方法名稱一樣)和識別。

方法的重載指的就是方法的名稱相同,但是參數不同。方法的重載和返回值沒有關系。

(1)如果參數的個數相同,那么參數的類型就不能相同。

(2)如果參數的類型相同,那么參數的個數就不能相同。

靜態成員使用經驗

1.靜態成員在程序運行時被調入內存中,並且在系統未關閉之前不會被GC回收。

2.類的成員使用非常頻繁時候,可以考慮使用static修飾,但是不要使用過多。

3.靜態成員不能直接調用實例成員(靜態方法不能直接調用實例方法)。

4.靜態方法也可以重載

 

方法的遞歸

方法自己調用自己。 

 

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace Panel
 8 {
 9     class Program
10     {
11         static void Main(string[] args)
12         {
13             Console.WriteLine("請輸入第一個數字");
14             string strNumberOne = Console.ReadLine();
15             int numberOne = GetNumber(strNumberOne);
16             Console.WriteLine("請輸入第二個數字");
17             string strNumberTwo = Console.ReadLine();
18             int numberTwo = GetNumber(strNumberOne);
19 
20             JudgeNumber(ref numberOne,ref numberTwo);
21             int sum = GetSum(numberOne,numberTwo);
22             Console.WriteLine(sum);
23             Console.ReadKey();
24 
25         }
26 
27         public static int GetNumber(string s)
28         {
29             while (true)
30             {
31                 try
32                 {
33                     int number = Convert.ToInt32(s);
34                     return number;
35                 }
36                 catch 
37                 {
38 
39                     Console.WriteLine("輸入有誤");
40                     s = Console.ReadLine();
41                 }
42                 
43             }
44         }
45 
46         public static void JudgeNumber(ref int n1,ref int n2)
47         {
48             while (true)
49             {
50                 if (n1 < n2)
51                 {
52                     return;
53                 }
54                 else
55                 {
56                     Console.WriteLine("第一個數字不能大於或等於第二個數字,青蟲滾輸入第一個數字");
57                     string s1 = Console.ReadLine();
58 
59                     n1 = GetNumber(s1);
60                     Console.WriteLine("請輸入第二個數字");
61                     string s2 = Console.ReadLine();
62                     n2 = GetNumber(s2);
63                 }
64             }
65         }
66 
67         public static int GetSum(int n1,int n2)
68         {
69             int sum = 0;
70             for (int i = n1; i <= n2; i++)
71             {
72                 sum += i;
73             }
74             return sum;
75         }
76     }
77 }



 
        


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM