C# ref 和out

ref 和out 相同点:都是按地址传递,使用后都将改变原来的数值

1. ref 关键字

   (1) 使用ref 关键字的注意点

        i. 方法定义和调用方法都必须使用ref 关键字

       ii.传递到ref 参数的参数必须初始化否则程序会报错

      iii. 通过ref 的这个特性,一定程度上解决了c# 中函数只能有一个返回值问题

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 6;
            int b = 66;
            Fun(ref a,ref b);
            Console.WriteLine("a:{0},b:{1}", a, b);//输出:72和6说明传入Fun方法是a和b的引用
        }
        static void Fun(ref int a, ref int b) {
            a = a+b;  //72,说明Main方法的a和b的值传进来了
            b = 6;
        }
    }
}

答案: a:72 ,b :6

2. out 关键字

   (1) 使用out 关键字的注意点

           i.   方法定义和调用方法都必须显式使用out关键字

           ii.  out 关键字无法将参数传递到out 参数所在的方法中,只能传递参数的引用,所以out参数的参数值初始化必须在其方法内进行否则程序会报错

           iii.   通过out 的这个特性,一定程度上解决了C# 中的函数只能有一个返回值的问题  

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int a=100;
            int b;
            Fun(out a, out b);
            Console.WriteLine("a:{0},b:{1}", a, b);//输出:3和1说明out参数传递进去的是a和b的引用,输出3说明a的参数值没有传入Fun方法中
        }
        static void Fun(out int a, out int b)
        {
            a = 1+2;
            b = 1;
        }
    }
}

答案是: a:3,b:1

 3. ref 和out 的区别

         通过上面的解析,ref 和out 主要的区别是

      ref   将参数的参数值和引用都传入方法中,所以ref 的参数的初始化必须在方法外部进行,也就是说 ref的参数必须有初始化值,否则程序会报错 。

      out 不会将参数的参数值传入方法中,只会将参数的引用传入方法中,所以参数的初始化工作必须在其      对用方法中进行,否则程序会报错

  4.  ref   和 out  的使用需要注意

    

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

namespace ConsoleApplication1
{
    class Program
    {

        public void SampleMethod(ref int i) { }
        public void SampleMethod(out int i) { }

    }
}

     无法定义重载方法 “SampleMethod” 因为它与其他方法仅在ref 和out 上有差别,尽管ref 和out 在运行时的处理方式不同,但是在编译时的处理方法是相同的,因此,如果一个   方法采用ref 参数,而另外一个采用out参数,则无法重载这两个方法。从编译的角度来看,一下代码中的两个方法是相同的,因此将不会编译上面的代码,但是,如果一个采用     ref 或out 参数,而另一个方法不采用这两个参数,则可以进行重载

http://chentian114.iteye.com/blog/2245639
原文地址:https://www.cnblogs.com/lghh/p/8554587.html