ref 和out的使用還有區別

廣義的說ref和out都是具有實現多個返回值的功能
區別在於out只進不出 ref又進又出
舉個例子 用out返回數組中最大值與最小值
static void MaxAndMin(int[] arr,out int min,out int max)
{
min = arr[0];
max = arr[0];
for (int i = 0; i < arr.Length; i++)
{
if (min>arr[i])
{
min = arr[i];
}
if (max< arr[i])
{
max = arr[i];
}
}
}
在Main方法中調用
int[] arr = { 1, 5, 8, 4, 20, 60, 13 };
int min = 0;
int max = 0;
MaxAndMin(arr,out min,out max);
Console.WriteLine(min+” “+max);

static void IndexOf(int[] arr,ref int index)
{
//index沒有進行初始化 最後還能傳出去
int count = 0;
for (int i = 0; i < arr.Length; i++)
{
if (arr[i] == index)
{
index = i;
break;
}
else {
count++;
}
}
if (count==arr.Length)
{
index = -1;
}
}
在Main方法中調用
int[] arr = { 1, 5, 8, 4, 20, 60, 13 };
int index = 8;
IndexOf(arr, ref index);
Console.WriteLine(index);

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章