C#中ref與out使用小結


使用ref前需要將變量初始化,而使用out前初始化與否都可以,ref傳遞的是參數的地址,out則是參數的返回值,ref傳遞的參數在函數退出時,賦值與否,編譯器都不會報錯;而out傳遞的參數則需要在退出函數時完成賦值操作。

示例如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyTest
{

    class Program
    {
        static void Method1(out int nNum)
        {
            nNum = 10;
        }

        static void Method2(ref int nNum)
        {
            nNum = 20;
        }

        static void Main(string[] args)
        {
            int n1;
            int n2 = 1;
            Console.WriteLine("n2 = {0}", n2);
            Method1(out n1);
            Method2(ref n2);
            Console.WriteLine("n1 = {0}", n1);
            Console.WriteLine("n2 = {0}", n2);
            Console.ReadKey();
        }
    }
}

 


免責聲明!

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



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