zl程序教程

您现在的位置是:首页 >  后端

当前栏目

C# 中的 ref 和 out 的意义和使用方法

c#方法 out 意义 ref 使用
2023-09-14 09:02:24 时间

原文C# 中的 ref 和 out 的意义和使用方法

 

  向方法传递一个实参时,对应的形参会用实参的一个副本来初始化,不管形参是值类型(例如 int),可空类型(int?),还是引用类型,这一点都是成立的。也就是随便在方法内部进行什么修改,都不会影响实参的值。例如,对于引用类型,方法的改变,只是会改变引用的数据,但实参本身并没有变化,它仍然引用同一个对象。

        代码如下:

 

    using System;  
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Text;  
      
    namespace ref_out  
    {  
        class Program  
        {  
            static void Main(string[] args)  
            {  
                int i = 8;  
                Console.WriteLine(i);  
                DoIncrease(i);  
                Console.WriteLine(i);  
            }  
      
            static void DoIncrease(int a)  
            {  
                a++;  
            }  
        }  
    }  

 

  运行结果如下:

      若使用 ref 关键字,向形参应用的任何操作都同样应用于实参,因为形参和实参引用的是同一个对象。

  PS:实参和形参都必须附加 ref 关键字做为前缀。

 

    using System;  
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Text;  
      
    namespace ref_out  
    {  
        class Program  
        {  
            static void Main(string[] args)  
            {  
                int i = 8;  
                Console.WriteLine(i);   // 8  
                DoIncrease(ref i);      // 实参前也必须加 ref  
                Console.WriteLine(i);   // 9 // ref 关键字使对形参的动作也应用于实参  
            }  
      
            static void DoIncrease(ref int a)   // 形参前必须加 ref  
            {  
                a++;  
            }  
        }  
    }  

 

 运行结果如下

ref 实参使用前也必须初始化,否则不能通过编译。

 

    using System;  
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Text;  
      
    namespace ref_out  
    {  
        class Program  
        {  
            static void Main(string[] args)  
            {  
                int i;          // ref 实参没有初始化,所以程序不能通过编译  
                Console.WriteLine(i);  
                DoIncrease(ref i);  
                Console.WriteLine(i);  
            }  
      
            static void DoIncrease(ref int a)  
            {  
                a++;  
            }  
        }  
    }  

 

有时我们希望由方法本身来初始化参数,这时可以使用 out 参数

代码如下:

 

    using System;  
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Text;  
      
    namespace ref_out  
    {  
        class Program  
        {  
            static void Main(string[] args)  
            {  
                int i;    // 没有初始化  
                //Console.WriteLine(i); // 此处 i 未初始化,编译错误  
                DoIncrease(out i);  // 用方法来给实参赋初值  
                Console.WriteLine(i);  
            }  
      
            static void DoIncrease(out int a)  
            {  
                a = 8;  // 在方法中进行初始化  
                a++;    // a = 9  
            }  
        }  
    }