ref和out關鍵字都是用來按地址傳遞的,使用後都將改變原來參數的數值。
ref
傳遞到 ref 參數的參數必須最先初始化。這與 out 不同,後者的參數在傳遞之前不需要顯式初始化。
class Program
{
static void Main(string[] args)
{
int a = 10;
int b = 20;
int result = calc.Add(ref a, ref b);
Console.WriteLine(result);
Console.ReadKey();
}
public class calc
{
public static int Add(ref int a,ref int b)
{
return a+b;
}
}
}
out
out 關鍵字會導致參數通過引用來傳遞。這與 ref 關鍵字類似,不同之處在於 ref 要求變量必須在傳遞之前進行初始化。若要使用 out 參數,方法定義和調用方法都必須顯式使用 out 關鍵字。
class Program
{
static void Main(string[] args)
{
int a = 10;
int b = 20;
int result = calc.Add(ref a, ref b);
Console.WriteLine(result);
Console.ReadKey();
}
public class calc
{
public static int Add(out int a, out int b)
{
a = 10;
b = 20;
return a + b;
}
}
}
注意
儘管 ref 和 out 在運行時的處理方式不同,但在編譯時的處理方式相同。因此,如果一個方法採用 ref 參數,而另一個方法採用 out 參數,則無法重載這兩個方法
下面的代碼會報錯:無法定義重載方法”Add”,因爲它與其他方法僅在ref和out上有差別
static void Main(string[] args)
{
int a = 10;
int b = 20;
int result = calc.Add(ref a, ref b);
result = calc.Add(out a, out b);//報錯
Console.WriteLine(result);
Console.ReadKey();
}
public class calc
{
public static int Add(out int a, out int b)
{
a = 10;
b = 20;
return a + b;
}
public static int Add(ref int a,ref int b)
{
return a+b;
}
}
但是,但是,如果一個方法採用 ref 或 out 參數,而另一個方法不採用這兩類參數,則可以進行重載,如下所示:
public class calc
{
public static int Add(int a,int b)
public static int Add(ref int a,ref int b)
}