代碼
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;
}
static void Main(string[] args)
{
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 .
這裡的輸出是指把函數體內的變數輸出到函數體外應用.這也關聯到了變數的範圍問題.