c#中的方法的定義和運用


首先,理解下,函數和方法:

其實兩者是一樣的,只是個叫法不同。

C#中叫做Method,中文叫方法;

C++中稱為Function,中文叫函數。

函數Function,多指以前面向過程編程時候,將邏輯編寫為一個一個過程,稱之為函數。

方法Method,是發展為面向對象的時候,代碼以類的方式來組織,類的里面是成員變量和成員函數,對應地也叫做數據和方法(method)。

下面代碼是簡單測試調用方法,這個方法用來判斷一個數是否是素數。

 1  1     using System;  
 2  2     using System.Collections.Generic;  
 3  3     using System.Linq;  
 4  4     using System.Text;  
 5  5       
 6  6     namespace main  
 7  7     {  
 8  8         //共同的命名空間中定義Program類,類中定義一個靜態方法(函數)Judge1和主函數Main函數。  
 9  9         class Program  
10 10         {  
11 11       
12 12             public static bool Judge1(int num)  
13 13             {  
14 14                 int i;  
15 15       
16 16                 for (i = 2; i < num; i++)  
17 17                 {  
18 18                     if (num % i == 0)  
19 19                     {  
20 20                         break;  
21 21                     }  
22 22                 }  
23 23       
24 24                 if (i == num)  
25 25                 {  
26 26                     return true;  
27 27                 }  
28 28                 else  
29 29                 {  
30 30                     return false;  
31 31                 }  
32 32             }  
33 33       
34 34             //主函數中調用Judgeclass類中的方法(函數)  
35 35             static void Main(string[] args)  
36 36             {  
37 37                 Console.WriteLine("輸入一個整數");  
38 38                 int i = int.Parse(Console.ReadLine());  
39 39                 Judgeclass.showisSushu(i);  
40 40       
41 41             }  
42 42         }  
43 43     } 
View Code

 

另外的一個類,這個類中有一個靜態方法:

 1 1 using System;  
 2  2 using System.Collections.Generic;  
 3  3 using System.Linq;  
 4  4 using System.Text;  
 5  5   
 6  6 namespace main  
 7  7 {  
 8  8     //在同一個命名空間中添加類,然后在類中定義方法(函數),在這個函數中調用另外一個類中的方法。  
 9  9     class Judgeclass  
10 10     {  
11 11         public static void showisSushu(int a)  
12 12         {  
13 13             if (Program.Judge1(a))  
14 14             {  
15 15                 Console.WriteLine("{0}是素數", a);  
16 16             }  
17 17             else  
18 18             {  
19 19                 Console.WriteLine("{0}不是素數", a);  
20 20             }  
21 21         }  
22 22     }  
23 23 }  
View Code

 


免責聲明!

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



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