天天看點

c#的三種參數傳遞方式

in型參數

int 型參數通過值傳遞的方式将數值傳入方法中,即我們在Java中常見的方法。

ref型參數

該種類型的參數傳遞變量位址給方法(引用傳遞),傳遞前變量必須初始化。

該類型與out型的差別在與:

1).ref 型傳遞變量前,變量必須初始化,否則編譯器會報錯, 而 out 型則不需要初始化

2).ref 型傳遞變量,數值可以傳入方法中,而 out 型無法将資料傳入方法中。換而言之,ref 型有進有出,out 型隻出不進。

out 型參數

與 ref 型類似,僅用于傳回結果。

注意:

1). out型資料在方法中必須要指派,否則編譯器會報錯。

eg:如下圖若将代碼中的sum1方法的方法體

改為 a+=b; 則編譯器會報錯。原因:out 型隻出不進,在沒給 a 指派前是不能使用的

改為 b+=b+2; 編譯器也會報錯。原因:out 型資料在方法中必須要指派。

2). 重載方法時若兩個方法的差別僅限于一個參數類型為ref 另一個方法中為out,編譯器會報錯

1 值傳遞 值傳遞對實參的值無任何影響

using System;

namespace CalculatorApplication

{

class NumberManipulator

{

public void swap(int x, int y)

{

int temp;

temp = x; /* 儲存 x 的值 */
     x = y;    /* 把 y 指派給 x */
     y = temp; /* 把 temp 指派給 y */
  }

  static void Main(string[] args)
  {
     NumberManipulator n = new NumberManipulator();
     /* 局部變量定義 */
     int a = 100;
     int b = 200;        
     Console.WriteLine("在交換之前,a 的值: {0}", a);//輸出100
     Console.WriteLine("在交換之前,b 的值: {0}", b);//輸出200
     /* 調用函數來交換值 */
     n.swap(a, b);        
     Console.WriteLine("在交換之後,a 的值: {0}", a);//輸出100
     Console.WriteLine("在交換之後,b 的值: {0}", b);//輸出200  前後不變
     Console.ReadLine();
  }
           

}

}

2引用傳遞 對實參也會做出改變 ref來定義

using System;

namespace CalculatorApplication

{

class NumberManipulator

{

public void swap(ref int x, ref int y)

{

int temp;

temp = x; /* 儲存 x 的值 */
     x = y;    /* 把 y 指派給 x */
     y = temp; /* 把 temp 指派給 y */
   }

  static void Main(string[] args)
  {
     NumberManipulator n = new NumberManipulator();
     /* 局部變量定義 */
     int a = 100;
     int b = 200;

     Console.WriteLine("在交換之前,a 的值: {0}", a);//100
     Console.WriteLine("在交換之前,b 的值: {0}", b);//200

     /* 調用函數來交換值 */
     n.swap(ref a, ref b);

     Console.WriteLine("在交換之後,a 的值: {0}", a);//200
     Console.WriteLine("在交換之後,b 的值: {0}", b);//100

     Console.ReadLine();

  }
           

}

}

3 按輸出傳遞參數 會改變實參 用out關鍵字來表示 可以輸出多個傳回值 使用前必須指派

using System;

namespace CalculatorApplication

{

class NumberManipulator

{

public void getValue(out int x )

{

int temp = 5;

x = temp;

}

static void Main(string[] args)
  {
     NumberManipulator n = new NumberManipulator();
     /* 局部變量定義 */
     int a = 100;

     Console.WriteLine("在方法調用之前,a 的值: {0}", a);//原來的值為100

     /* 調用函數來擷取值 */
     n.getValue(out a); 

     Console.WriteLine("在方法調用之後,a 的值: {0}", a);//調用方法後的值為5
     Console.ReadLine();

  }
           

}

}

c#