c# - ref 和 out 值类型变量

标签 c# methods out ref

msdn documentation on out表示作为 out 传递的参数必须在函数内部分配一个值。网站示例:

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

根据我的理解,当声明 int “值”时,它已经被分配了一个默认值 0(因为 int 是一个值类型并且不能为 null。)那么为什么“方法”有必要修改它的值?

同理,如果用“ref”代替out,是否需要初始化“value”?

有这样的问题What's the difference between the 'ref' and 'out' keywords?但没有人愿意将 2 和 2 放在一起。

最佳答案

According to my understanding when the int "value" is declared it is already assigned a default value of 0 (since int is a value type and cannot be null.)

不,那是不正确的。

局部变量在创建时没有被赋值。局部变量的空间是通过移动堆栈指针在堆栈上为它们腾出空间来创建的。该内存区域不会被清除,它将包含恰好存在的所有值。

编译器强制你在变量可以使用之前给它赋值,这样它原本包含的“垃圾”值将永远不会被使用。

Similarly, if "ref" were to be used instead of out, would there be any need of initializing "value"?

不需要在方法中设置该值,因为它已经有一个值。用于调用该方法的变量需要初始化:

static void Method(ref int i) {
    // doesn't need to set the value
}

static void Main() {
    int value;
    value = 42; // needs to be initialised before the call
    Method(ref value);
   // value is still 42
}

关于c# - ref 和 out 值类型变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29635754/

相关文章:

c# - 如何在 C# 中从 Google map 获取高程点?

c# - 如何使用 LINQ 在一个集合中选择一个集合?

c# - 在抛出未处理的 JavaScript 错误之前,不查询 IServiceProvider IElementBehaviorFactory

C# 7 Out 变量和模式变量声明不允许在查询子句中

java - SYSO(System.out.println())的作用是什么?

c# - BackgroundWorker,方法

java - 当任何一个 ListArray 具有重复元素时,计算 ListArray 的数量

java - Java中两个不同数组之间的数字相除

iphone - 执行选择器 :withObject:afterDelay method not working properly?

C# out参数值传递