0
点赞
收藏
分享

微信扫一扫

ref out 关键字用法与区别详解


ref 关键字使参数按引用传递。其效果是,当控制权传递回调用方法时,在方法中对参数的任何更改都将反映在该变量中。若要使用 ref 参数,则方法定义和调用方法都必须显式使用 ref 关键字。例如:


class  RefOutOverloadExample
{
public void SampleMethod( int i) { }
public void SampleMethod( ref int i) { }
}


 
按引用传递值类型(如本主题前面所示)是有用的,但是 ref 对于传递引用类型也是很有用的。这允许被调用的方法修改该引用所引用的对象,因为引用本身是按引用来传递的。下面的示例显示出当引用类型作为 ref 参数传递时,可以更改对象本身。

class  RefRefExample
{
static void Method( ref string s)
{
s = " changed " ;
}
static void Main()
{
string str = " original " ;
Method( ref str);
// str is now "changed"
}
}


 


参数传递可分值传递,引用传递。 
引用类型都是引用传递,就是对传递进去的变量的修改会反映在原来的变量上, 
值类型 当不用 out或者 ref的时候就是 值传递,就是对传递进去的变量的修改不会反映在原来的变量上,修改的只是原来变量的一个副本。 
加上 out或者 ref可以实现值类型的引用传递


 

out 关键字会导致参数通过引用来传递。这与 ref 关键字类似,不同之处在于 ref 要求变量必须在传递之前进行初始化。若要使用 out 参数,方法定义和调用方法都必须显式使用 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) { }
}


 

尽管作为 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  RefOutOverloadExample
{
public void SampleMethod( int i) { }
public void SampleMethod( out int i) { }
}


ref 关键字使参数按引用传递。其效果是,当控制权传递回调用方法时,在方法中对参数的任何更改都将反映在该变量中。若要使用 ref 参数,则方法定义和调用方法都必须显式使用 ref



class  RefExample
{
static void Method( ref int i)
{
i = 44 ;
}
static void Main()
{
int val = 0 ;
Method( ref val);
// val is now 44
}
}


 

传递到 ref 参数的参数必须最先初始化。这与 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( ref int i) { }
public void SampleMethod( out int i) { }
}


 

但是,如果一个方法采用 ref 或 out


class  RefOutOverloadExample
{
public void SampleMethod( int i) { }
public void SampleMethod( ref int i) { }
}

作者:鹏鹏 Lovely

举报

相关推荐

0 条评论