c#中ref和out的區別
當希望方法返回多個值時,聲明 out 方法非常有用。使用 out 參數的方法仍然可以返回一個值。一個方法可以有一個以上的 out 參數。
若要使用 out 參數,必須將參數作爲 out 參數顯式傳遞到方法。out 參數的值不會傳遞到 out 參數。
不必初始化作爲 out 參數傳遞的變量。然而,必須在方法返回之前爲 out 參數賦值。
屬性不是變量,不能作爲 out 參數傳遞。
方法參數上的 ref 方法參數關鍵字使方法引用傳遞到方法的同一個變量。當控制傳遞迴調用方法時,在方法中對參數所做的任何更改都將反映在該變量中。
若要使用 ref 參數,必須將參數作爲 ref 參數顯式傳遞到方法。ref 參數的值被傳遞到 ref 參數。
傳遞到 ref 參數的參數必須最先初始化。將此方法與 out 參數相比,後者的參數在傳遞到 out 參數之前不必顯式初始化。
屬性不是變量,不能作爲 ref 參數傳遞。
也就是說ref類似於c語言中的指針。
using System;
class Account
{
private int balance = 0; //字段
public int Balance //屬性
{
get { return balance; }
set { balance = value;}
}
public void Deposit(int n)
{ this.balance += n; }
public void WithDraw(int n)
{ this.balance -= n; }
}
class Client
{
public static void Main()
{
Account a = new Account();
a.Balance = 1000; // 可以讀寫屬性,因爲屬性Balance是public型的
//a.balance = 1000; //不可以讀寫字段,因爲字段balance是private型的
a.WithDraw(500);
a.Deposit(2000);
Console.WriteLine("before Method call: a.balance = {0}", a.Balance);
int x = 1;
int y = 100;
int z;
AMethod(x, ref a.balance ,out z); //ref a.balance 正確,a.balance是字段變量
//AMethod(x, ref a.Balance ,out z); //ref a.Balance 錯誤,a.Balance是屬性
y = a.balance;
Console.WriteLine("After Method Call : x = {0}, y = {1}, z = {2}", x, y, a.balance);
AMethod(x, ref y ,out a.balance); //out a.balance 正確,a.balance是字段變量
//AMethod(x, ref y ,out a.Balance); //ref a.Balance 錯誤,a.Balance是字段變量
z = a.balance;
Console.WriteLine("After Method Call : x = {0}, y = {1}, z = {2}", x, y, a.balance);
AMethod(x, ref y ,out z);
Console.WriteLine("After Method Call : x = {0}, y = {1}, z = {2}", x, y, z);
}
public static void AMethod(int x, ref int y, out int z)
{
x = 7;
y = 8;
z = 9;
}
}
輸出結果:
---------- C# Run ----------
before Method call: a.balance = 2500
After Method Call : x = 1, y = 8, z = 8
After Method Call : x = 1, y = 8, z = 9
After Method Call : x = 1, y = 8, z = 9
輸出完成 (耗時: 0 秒) - 正常終止