木子屋 Dnawo's BLOG

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

👤 dnawo 📅 2008-09-26 👁 5330 👍 0 💬 0 🔄 来源:本站原创
相同点:都可以改变变量的值;
不同点: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)

暂无评论。

验证码
评论需审核通过后显示
← 上一篇 ASP.NET页面中获取get方式发送过来任何编码的数据 下一篇 → 批处理切换本机IP、网关和DNS