
代碼
static int xValue(ref int num, ref int num2)
{
num = 2 * num;
num2 = 2 * num2;
return num;
}
static void Main(string[] args)
int num = 5;
int num2 = 10;
Console.WriteLine(xValue(ref num, ref num2));
Console.WriteLine(num + ":" + num2);
//這時的num=10, num2=20;輸出結果:10:20;加上ref後會影響到函數外面的變量
兩個注意點:
1:定義函數時.指定參數的資料類型與函數體外面定義的變量類型一緻,static int xValue(ref int num, ref int num2)
2:使用此函數時為每個參數加上ref.如果不加的話則不會影響函數外面變量的值

static int MaxValueL(int[] numArry, out int maxIndex, out int maxIndex2)
int MaxValue = numArry[0];
maxIndex = 0;
maxIndex2 = 100;
for (int i = 1; i < numArry.Length; i++)
{
if (MaxValue < numArry[i])
{
MaxValue = numArry[i];
maxIndex = i;
}
}
return MaxValue;
int maxIndex;
int maxIndex2;
int[] numArr = { 14, 3, 34, 11, 99, 33 };
Console.WriteLine(MaxValueL(numArr, out maxIndex, out maxIndex2));
//傳回函數體内的變量MaxValue
Console.WriteLine(maxIndex + 1);
//傳回函數體内的變量maxIndex
Console.WriteLine(maxIndex2);
//傳回函數體内的變量maxIndex2
Console.ReadKey();
1:定義函數時.指定輸出參數的資料類型與函數體外面定義的變量類型一緻,out int maxIndex, out int maxIndex2
2:使用此函數時為想要輸出參數加上 out .
這裡的輸出是指把函數體内的變量輸出到函數體外應用.這也關聯到了變量的作用域問題.