Ref and out in C # using Summary

You need to initialize variables before using ref, while the former can use out initialization or not, ref transfer is the address parameters, return values ​​are out parameters, ref parameters passed when the function exits, assignment or not, the compiler without error; and parameter passing out of the need to complete the assignment at the time of exit.

Examples are as follows:

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();
        }
    }
}

 

Guess you like

Origin www.cnblogs.com/QingYiShouJiuRen/p/11353896.html