值引數
1、在堆疊中為形參分配空間
2、復制實參到形參
1 public class Person 2 { 3 public int age = 10; 4 } 5 static void Main(string[] args) 6 { 7 int a2= 10; 8 Person a1= new Person(); 9 10 Console.WriteLine(a1.age + "--" + a2); 11 SetParam(a1, a2); 12 Console.WriteLine(a1.age + "--" + a2); 13 Console.ReadLine(); 14 } 15 static void SetParam(Person f1, int f2) 16 { 17 f1.age = f1.age + 5; 18 f2 = f2 + 5; 19 }
上面的輸出結果是
10--5
15--5

參考引數
1、使用參考引數時,必須在方法的宣告和呼叫中都使用ref修飾符,
2、實參必須是變數,在用作實參前必須被賦值,如果是參考型別的變數,可以賦值為一個參考或null值,
3、不在堆疊中為形參分配新的記憶體,
4、形參名稱相當于實參變數的別名,參考與實參相同的記憶體位置,
1 public class Person 2 { 3 public int age = 10; 4 } 5 static void Main(string[] args) 6 { 7 int a2 = 5; 8 Person a1 = new Person(); 9 10 Console.WriteLine(a1.age + "--" + a2); 11 SetParam(ref a1,ref a2); 12 Console.WriteLine(a1.age + "--" + a2); 13 14 Console.ReadLine(); 15 16 17 } 18 19 static void SetParam(ref Person f1,ref int f2) 20 { 21 f1.age = f1.age + 5; 22 f2 = f2 + 5; 23 }
上面的輸出結果是
10--5
15--10

輸出引數
1、必須在宣告的呼叫中都是用修飾符,輸出引數的修飾符是out而不是ref,
2、實參不許是變數,不能是其他運算式型別,
3、在方法內部,輸出引數在被讀取之前必須被賦值,這意味著引數的初始值是無關的,而且沒有必要在方法呼叫前為實參賦值,
4、每個輸出引數在方法回傳之前必須被賦值
1 public class Person 2 { 3 public int age = 10; 4 } 5 static void Main(string[] args) 6 { 7 Person a1 = null; 8 int a2; 9 10 OutParam(out a1,out a2); 11 Console.WriteLine(a1.age + "--" + a2); 12 Console.ReadLine(); 13 } 14 15 static void OutParam(out Person f1, out int f2) 16 { 17 f1 = new Person(); 18 f1.age = 25; 19 f2 = 15; 20 }
上面的輸出結果是
25--15

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/191105.html
標籤:.NET技术
