c# 中ref 和out的区别

学习c# 也差不多两年了。这几周一直都在重温C#的知识点。ref和out的区别到今天为止总算是彻底的明白了。

两者之间的共同点是:两者都是传递参数地址。都能改变参数的值。

如例子中的传递参数num和num2,经过计算两者的值都发生了改变;如果不用ref和out的关键字。num和num2 的值依然为10。

不同点:1。ref 可以传进传出,而out的只出不进。

如例子中的Func() 中使用了out的关键字。如果在函数体中不对参数指定值。程序是会出错的。而该函数会把i=2012的值传到外面。

而 ref可以将参数的值传到FunC中,也可以将Func中定义的参数的值传出。如Sample 2 中的方法。

                                           SAMPLE 2
static
void FunC(ref int i) { int i=2012; }

而out的,不能采用Sample 1 中的 FunC() 使用的方法。

                                             SAMPLE 1
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int num = 10;
            int num2=10;
            num = num * 2;
         
            Func(ref num);

            FunC(out num2);
            num2 = num2 * 2;
            Console.WriteLine("num的值为:{0}",num);
            Console.WriteLine("num2的值为:{0}", num2);
            Console.ReadKey();
        }
        static void Func(ref int i)
        { 
           
          
        }
        static void FunC(out int i)
        {

            i = 2012;
        }
    }
}

                           

原文地址:https://www.cnblogs.com/myyouthlife/p/2623435.html