54.C#函數參數out、ref的使用以及Python

函數參數out、ref都是向外傳遞參數值,以彌補返回值只有一個的缺陷。函數參數可以有多個out參數,因此這樣的函數返回的數據是開放的。out和ref的區別是out不用爲out參數附初值,而ref必須附初值。

python可以return可以返回多個參數,一般不必要使用out和ref參數。這降低了python的難度。


public static void FillArray(out int[] arr)
{
    arr = new int[] { 1, 2, 3, 4, 5 };
}

public static void FillArrayRef(ref int[] arrRef)
{
    arrRef = new int[] { 6, 7, 8, 9, 0 };
}

public static void MaxMinValue(int[] intArray, out int max, out int maxIndex)
{
    max = intArray[0];
    maxIndex = 0;
    for(int i=1;i<intArray.Length;i++)
    {
        if (intArray[i] > max)
        {
            max = intArray[i];
            maxIndex = i;
        }
    }
}
static void Main(string[] args)
{
    //用out參數填充數組
    int[] theArray;//不用初始化
    useout.FillArray(out theArray);
    Console.WriteLine("theArray:");
    foreach(int i in theArray)
    {
        Console.Write(i);
        Console.Write(" ");
    }

    //用ref參數填充數組
    int[] arrRef = new int[5];//需要初始化
    useout.FillArrayRef(ref arrRef);
    Console.WriteLine();
    Console.WriteLine("arrRef:");
    foreach(int i in arrRef)
    {
        Console.Write(i);
        Console.Write(" ");
    }

    //找出最大年齡及序號:
    int[] age = { 34, 24, 65, 76, 39, 57, 89 };
    int max = 0;
    int maxIndex=0;

    useout.MaxMinValue(age, out max, out maxIndex);
    Console.WriteLine();
    Console.WriteLine($"年齡最大的是:{max},序號是{maxIndex+1}");
}

輸出是:

python就沒有這麼多說道了,一般不需要out參數,因爲python可以返回不止一個返回值。

def maxminValue(alist):
    x=max(alist);
    y=min(alist);
    return x,y
a,b=maxminValue([3,2,5,4,8,6,9])
print(a,b)#輸出9,2

或者使用全局變量“global”來返回out參數。

def maxminValue(alist):
    global x,y#不能爲global變量直接賦值。
    x=max(alist)
    y=min(alist)
    return x+y,x*y
a,b=maxminValue([3,2,5,4,8,6,9])
print(a,b)#11,18
print(x,y)#9,2

 

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