C# 基礎知識復習(三)---方法參數傳遞
阿新 • • 發佈:2017-09-09
val 相同 clas 沒有 tel cal 引用傳遞 局部變量 調用
一個方法是把一些相關的語句組織在一起,用來執行一個任務的語句塊。每一個 C# 程序至少有一個帶有 Main 方法的類。
要使用一個方法,您需要:
- 定義方法
- 調用方法
按值傳遞參數
這是參數傳遞的默認方式。在這種方式下,當調用一個方法時,會為每個值參數創建一個新的存儲位置。
實際參數的值會復制給形參,實參和形參使用的是兩個不同內存中的值。所以,當形參的值發生改變時,不會影響實參的值,從而保證了實參數據的安全。
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);
Console.WriteLine("在交換之前,b 的值: {0}", b);
/* 調用函數來交換值 */
n.swap(a, b);
Console.WriteLine("在交換之後,a 的值: {0}", a);
Console.WriteLine("在交換之後,b 的值: {0}", b);
Console.ReadLine();
}
}
}
當上面的代碼被編譯和執行時,它會產生下列結果:
在交換之前,a 的值:100
在交換之前,b 的值:200
在交換之後,a 的值:100
在交換之後,b 的值:200
結果表明,即使在函數內改變了值,值也沒有發生任何的變化
按引用傳遞參數
引用參數是一個對變量的內存位置的引用。當按引用傳遞參數時,與值參數不同的是,它不會為這些參數創建一個新的存儲位置。引用參數表示與提供給方法的實際參數具有相同的內存位置。
在 C# 中,使用 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); Console.WriteLine("在交換之前,b 的值: {0}", b); /* 調用函數來交換值 */ n.swap(ref a, ref b); Console.WriteLine("在交換之後,a 的值: {0}", a); Console.WriteLine("在交換之後,b 的值: {0}", b); Console.ReadLine(); } } }
當上面的代碼被編譯和執行時,它會產生下列結果:
在交換之前,a 的值:100
在交換之前,b 的值:200
在交換之後,a 的值:200
在交換之後,b 的值:100
結果表明,swap 函數內的值改變了,且這個改變可以在 Main 函數中反映出來
按輸出傳遞參數
return 語句可用於只從函數中返回一個值。但是,可以使用 輸出參數 來從函數中返回兩個值。輸出參數會把方法輸出的數據賦給自己,其他方面與引用參數相似。
下面的實例演示了這點:
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);
/* 調用函數來獲取值 */
n.getValue(out a);
Console.WriteLine("在方法調用之後,a 的值: {0}", a);
Console.ReadLine();
}
}
}
當上面的代碼被編譯和執行時,它會產生下列結果:
在方法調用之前,a 的值: 100
在方法調用之後,a 的值: 5
C# 基礎知識復習(三)---方法參數傳遞