C#中引用參數ref和輸出參數out


引用參數 用於按引用傳遞自變量。 為引用參數傳遞的自變量必須是具有明確值的變量,並且在方法執行期間,引用參數指明的存儲位置與自變量相同。 引用參數使用 ref 修飾符進行聲明。 

輸出參數 用於按引用傳遞自變量。 輸出參數與引用參數類似,不同之處在於,不要求向調用方提供的自變量顯式賦值。 輸出參數使用 out 修飾符進行聲明。 下面分別示例展示了如何使用 ref out  關鍵字

using System;

class RefExample
{
    static void Swap(ref int x, ref int y)
    {
        int temp;
        temp = x;
        x = y;
        y = temp;

    }
    public static void SwapExample()
    {
        int i = 1, j = 2;
        Swap(ref i,ref j);
        Console.WriteLine($"{i}{j}");
    }

    /*static void Main(string[] args)
    {
        SwapExample();
    }
    */
}
class OutExample
{
    static void Divide(int x, int y,out int result,out int remainder)
    {
        result = x / y;
        remainder = x % y;

    }

    public static void OutUsage()
    {
        Divide(10, 3, out int res, out int rem);
        Console.WriteLine("{0} {1}", res, rem);
    }

    static void Main()
    {
        OutUsage();
        RefExample.SwapExample();
        
        

    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM