方法是什麼 方法是C#中將一堆代碼進行進行重用的機制 他是在類中實現一種特定功能的代碼塊,將重覆性功能提取出來定義一個新的方法 這樣可以提高代碼的復用性,使編寫程式更加快捷迅速 方法格式 訪問修飾符 返回類型 方法名稱(參數列表) { 方法體; } 方法是在類或結構中聲明的,聲明時需要訪問修飾符、返 ...
方法是什麼
方法是C#中將一堆代碼進行進行重用的機制
他是在類中實現一種特定功能的代碼塊,將重覆性功能提取出來定義一個新的方法
這樣可以提高代碼的復用性,使編寫程式更加快捷迅速
方法格式
訪問修飾符 返回類型 方法名稱(參數列表)
{
方法體;
}
方法是在類或結構中聲明的,聲明時需要訪問修飾符、返回類型、方法名稱、參數列表、方法體
訪問修飾符:聲明方法對另一個類的可見性,如public、protect
返回類型:方法可以有返回值也可以無返回值,無返回值時為void,有返回值時需要聲明返回值得數據類型
方法名稱:方法的標識符,對大小寫敏感
參數列表:使用小括弧括起來,跟在方法名稱的後面,用來接收和傳遞方法的數據。可以有也可以無,根據需要確定
方法主體:方法所執行的指令集合
示例
1 using System; 2 3 namespace NumberSwap 4 { 5 class NumberManipulator 6 { 7 public int swap(ref int x, ref int y) //返回值為int類型 8 { 9 int temp; 10 11 temp = x; 12 x = y; 13 y = temp; 14 15 int sum = x + y; 16 return sum; 17 } 18 19 static void Main(string[] args) 20 { 21 NumberManipulator n = new NumberManipulator(); 22 23 int a = 100; 24 int b = 200; 25 26 n.swap(ref a, ref b); //調用方法 27 Console.WriteLine("調用方法swap後a的值:{0}", a); 28 Console.WriteLine("調用方法swap後b的值:{0}", b); 29 30 Console.WriteLine("兩數之和為:{0}", n.swap(ref a, ref b)); 31 } 32 } 33 }
結果
方法重載
方法重載是在一個類中定義多個方法名相同、方法間參數個數和參數順序不同的方法
方法重載是讓類以統一的方式處理不同類型數據的一種手段
方法重載定義時有以下四個要求:
方法名稱必須相同
參數個數必須不同(如果參數個數相同,那麼類型必須不同)
參數類型必須不同
和返回值無關
示例
1 using System; 2 3 namespace Calculator 4 { 5 class Program 6 { 7 /// <summary> 8 /// 方法重載:無參 9 /// </summary> 10 static void overloaded_func() 11 { 12 Console.WriteLine("方法重載,無參"); 13 } 14 15 /// <summary> 16 /// 方法重載:1個整型參數 17 /// </summary> 18 static void overloaded_func(int x) 19 { 20 Console.WriteLine("方法重載,一個整型參數"); 21 } 22 23 /// <summary> 24 /// 方法重載:1個字元串參數 25 /// </summary> 26 static void overloaded_func(string str) 27 { 28 Console.WriteLine("方法重載,一個字元串參數"); 29 } 30 31 /// <summary> 32 /// 方法重載:2個參數 33 /// </summary> 34 static void overloaded_func(int x, string str) 35 { 36 Console.WriteLine("方法重載,兩個參數"); 37 } 38 39 40 static void Main(string[] args) 41 { 42 // 方法重載1 43 overloaded_func(); 44 // 方法重載2 45 overloaded_func(1); 46 // 方法重載3 47 overloaded_func(1, "重載"); 48 } 49 } 50 }
結果