Skip to main content
 首页 » 编程设计

c#之ref 和 out 值类型变量

2024年02月06日16mate10pro

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 
}