C#函数ref和out参数的区别

相同点:都可以改变变量的值;
不同点:ref参数必须先赋值,out参数不必先赋值,在函数体中都当作未赋值;
其他:不能定义仅在 ref 和 out 上有差别的重载方法;

protected void Page_Load(object sender, EventArgs e)
{
    int a;
    Test_ref(ref a);
}

protected void Test_ref(ref int num)
{
    num++;
}

Error:使用了未赋值的局部变量“a”

protected void Page_Load(object sender, EventArgs e)
{
    int a = 8;
    Test_out(out a);
}

protected void Test_out(out int num)
{
    num++;
}

Error:使用了未赋值的 out 参数“num”

protected void Test(ref int num)
{
    num++;
}

protected void Test(out int num)
{
    num = 1;
}

Error:“Test”不能定义仅在 ref 和 out 上有差别的重载方法

评论: 0 | 引用: 0 | 查看次数: 4865
发表评论
登录后再发表评论!