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

📅  最后修改于: 2021-05-29 16:13:02             🧑  作者: Mango

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#中的关键字,用于通过引用传递参数。或者我们可以说,当控件返回到调用方法时,如果对方法中的此参数进行的任何更改都将反映在该变量中。 ref参数不传递该属性。

例子:

// 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 = "GeeksforGeeks";
    }
}

输出:

Hello!!Geek
GeeksforGeeks
Ref和Out关键字之间的区别
ref keyword out keyword
It is necessary the parameters should initialize before it pass to ref. It is not necessary to initialize parameters before it pass to out.
It is not necessary to initialize the value of a parameter before returning to the calling method. It is necessary to initialize the value of a parameter before returning to the calling method.
The passing of value through ref parameter is useful when the called method also need to change the value of passed parameter. The declaring of parameter through out parameter is useful when a method return multiple values.
When ref keyword is used the data may pass in bi-directional. When out keyword is used the data only passed in unidirectional.

注意: refout参数在编译时相同,但在运行时不同。