out 和 ref 参数修饰符

Posted 王.小辉

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了out 和 ref 参数修饰符相关的知识,希望对你有一定的参考价值。

整理自MSDN

out:

out 关键字通过引用传递参数。这与 ref 关键字相似,只不过 ref 要求在传递之前初始化变量。若要使用 out 参数,方法定义和调用方法均必须显式使用 out 关键字。例如:

class OutExample
{
    static void Method(out int i)
    {
        i = 44;
    }
    static void Main()
    {
        int value;
        Method(out value);
        // value is now 44
    }
}

尽管作为 out 参数传递的变量无需在传递之前初始化,调用方法仍要求在方法返回之前赋值

尽管 ref 和 out 关键字会导致不同的运行时行为,它们并不被视为编译时方法签名的一部分。因此,如果唯一的不同是一个方法采用 ref 参数,而另一个方法采用 out 参数,则无法重载这两个方法。例如,以下代码将不会编译:

class CS0663_Example
{
    // Compiler error CS0663: "Cannot define overloaded 
    // methods that differ only on ref and out".
    public void SampleMethod(out int i) { }
    public void SampleMethod(ref int i) { }
}

但是,如果一个方法采用 ref 或 out 参数,而另一个方法采用其他参数,则可以完成重载,如:
class OutOverloadExample
{
    public void SampleMethod(int i) { }
    public void SampleMethod(out int i) { i = 5; }
}
属性不是变量,因此不能作为 out 参数传递。

 

 

ref:

ref 关键字会导致参数通过引用传递,而不是通过值传递。 通过引用传递的效果是,对所调用方法中的参数进行的任何更改都反映在调用方法中。例如,如果调用方传递本地变量表达式或数组元素访问表达式,所调用方法会将对象替换为 ref 参数引用的对象,然后调用方的本地变量或数组元素将开始引用新对象。

若要使用 ref 参数,方法定义和调用方法均必须显式使用 ref 关键字,如下面的示例所示。

class RefExample
{
    static void Method(ref int i)
    {
        // Rest the mouse pointer over i to verify that it is an int.
        // The following statement would cause a compiler error if i
        // were boxed as an object.
        i = i + 44;
    }

    static void Main()
    {
        int val = 1;
        Method(ref val);
        Console.WriteLine(val);

        // Output: 45
    }
}

 

传递到 ref 形参的实参必须先经过初始化,然后才能传递这与 out 形参不同,在传递之前,不需要显式初始化该形参的实参。有关详细信息,请参阅 out

类的成员不能具有仅在 ref 和 out 方面不同的签名。如果类型的两个成员之间的唯一区别在于其中一个具有 ref 参数,而另一个具有 out 参数,则会发生编译错误。

以上是关于out 和 ref 参数修饰符的主要内容,如果未能解决你的问题,请参考以下文章

方法参数修饰符in,out,ref

refout 修饰符

C# 基础 访问修饰符ref与out标志枚举等等

C# 中的 in 参数和性能分析

C#值参数和引用参数,方法的重载,foreach,数组,以及ref和out的用法

out 和 ref + params 的理解