C#使用out和ref傳遞數組參數


      閑來無聊拿着公司之前的asp.net項目看,重新激發了我學C#的沖動,哇咔咔~~~畢竟它太優雅了~

      人懶手不勤,腦子再好用都是白搭,現在就開始貼我自學的漫漫過程吧,給未來的自己感謝自己的理由!!

今天說說ref和out    

  ref所傳的參數必須由調用方明確賦值,被調用方可以對其進行修改;

  out所傳的參數就不必由調用方明確賦值了.

  將這層意思應用到數組類型的參數上,也就是說,ref傳遞的數組必須是調用函數里已經初始化好的,而被調函數可對其進行某些元素的在賦值或者初始化.

  使用out傳遞數組就無所謂是不是已在主調函數中初始化好的了.

貼個例子(取自C#編程指南):

class TestOut
{
    static void FillArray(out int[] arr)
    {
        // Initialize the array:
        arr = new int[5] { 1, 2, 3, 4, 5 };
    }

    static void Main()
    {
        int[] theArray; // Initialization is not required

        // Pass the array to the callee using out:
        FillArray(out theArray);

        // Display the array elements:
        System.Console.WriteLine("Array elements are:");
        for (int i = 0; i < theArray.Length; i++)
        {
            System.Console.Write(theArray[i] + " ");
        }

        // Keep the console window open in debug mode.
        System.Console.WriteLine("Press any key to exit.");
        System.Console.ReadKey();
    }
}
    /* Output:
        Array elements are:
        1 2 3 4 5        
    */
***********************************************************************************************************************************************************
class TestRef
{
    static void FillArray(ref int[] arr)
    {
        // Create the array on demand:
        if (arr == null)
        {
            arr = new int[10];
        }
        // Fill the array:
        arr[0] = 1111;
        arr[4] = 5555;
    }

    static void Main()
    {
        // Initialize the array:
        int[] theArray = { 1, 2, 3, 4, 5 };

        // Pass the array using ref:
        FillArray(ref theArray);

        // Display the updated array:
        System.Console.WriteLine("Array elements are:");
        for (int i = 0; i < theArray.Length; i++)
        {
            System.Console.Write(theArray[i] + " ");
        }

        // Keep the console window open in debug mode.
        System.Console.WriteLine("Press any key to exit.");
        System.Console.ReadKey();
    }
}
    /* Output:
        Array elements are:
        1111 2 3 4 5555
    */

 

 


免責聲明!

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



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