整理自MSDN

out:

例如:

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

尽管作为 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 关键字,如下面的示例所示。

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
    }
}

 

out。


相关文章: