个性化阅读
专注于IT技术分析

C#中Ref和Out关键字之间的区别

点击下载

Out是C#中的关键字, 用于将参数作为引用类型传递给方法。通常在方法返回多个值时使用。 out参数不会传递该属性。

示例:

//C# program to illustrate the
//concept of out parameter
using System;
  
class GFG {
  
     //Main method
     static public void Main()
     {
  
         //Declaring variable
         //without assigning value
         int G;
  
         //Pass variable G to the method
         //using out keyword
         Sum( out G);
  
         //Display the value G
         Console.WriteLine( "The sum of" + 
                 " the value is: {0}" , G);
     }
  
     //Method in which out parameter is passed
     //and this method returns the value of
     //the passed parameter
     public static void Sum( out int G)
     {
         G = 80;
         G += G;
     }
}

输出如下:

The sum of the value is: 160

Ref是C#中的关键字, 用于通过引用传递参数。或者我们可以说, 当控件返回到调用方法时, 如果对方法中的此参数进行的任何更改都将反映在该变量中。的参考参数未通过属性.

例子:

//C# program to illustrate the
//concept of ref parameter
using System;
  
class GFG {
  
     //Main Method
     public static void Main()
     {
  
         //Assign string value
         string str = "Geek" ;
  
         //Pass as a reference parameter
         SetValue( ref str);
  
         //Display the given string
         Console.WriteLine(str);
     }
  
     static void SetValue( ref string str1)
     {
  
         //Check parameter value
         if (str1 == "Geek" ) {
             Console.WriteLine( "Hello!!Geek" );
         }
  
         //Assign the new value
         //of the parameter
         str1 = "srcmini" ;
     }
}

输出如下:

Hello!!Geek
srcmini
Ref和Out关键字之间的区别
ref关键字 out关键字
参数必须在传递给ref之前初始化。 传递给输出之前, 无需初始化参数。
返回调用方法之前, 不必初始化参数的值。 返回到调用方法之前, 必须初始化参数的值。
当被调用的方法也需要更改传递参数的值时, 通过ref参数传递值很有用。 当方法返回多个值时, 通过out参数声明参数非常有用。
使用ref关键字时, 数据可能双向传递。 使用out关键字时, 数据仅以单向传递。

注意:ut和ref在编译时相同, 但在运行时不同。


赞(0)
未经允许不得转载:srcmini » C#中Ref和Out关键字之间的区别

评论 抢沙发

评论前必须登录!