C#学习:函数的ref、out参数

函数参数默认是值传递的,也就是“复制一份”,通过函数的处理对数值本身并没有影响,如果函数想对数值本身产生影响就需要使用相应的参数。

ref必须先初始化,因为是引用,所以必须先“有”,才能引用。使用ref如果未进行初始化,将报出如图所示的错误使用了未赋值的局部变量“age”:

加上ref之后传参传的是引用而不再是没加ref时的拷贝。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace refout参数
{
    class Program
    {
        static void Main(string[] args)
        {
            int age;
            IncAge(ref age); 
            Console.WriteLine(age);
            Console.ReadKey();
        }
      
        static void IncAge(ref int age)
        {
            age++;
        }
      
    }
}

out是内部为外部赋值,所以不需要初始化,而且初始化也没用。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace refout参数
{
    class Program
    {
        static void Main(string[] args)
        {
            int age;
            IncAge(out age); 
            Console.WriteLine(age);
            Console.ReadKey();
        }
      
        static void IncAge(out int age)
        {
            age=20;
        }
      
    }
}

执行结果:

总结:ref应用场景内部对外部的值进行改变,out则是内部为外部变量赋值,out一般用在函数有多个返回值的场所

out应用举例:int.TryParse

int.Parse()是一种类容转换;表示将数字内容的字符串转为int类型。
如果字符串为空,则抛出ArgumentNullException异常;
如果字符串内容不是数字,则抛出FormatException异常;
如果字符串内容所表示数字超出int类型可表示的范围,则抛出OverflowException异常;
int.TryParse 与 int.Parse 又较为类似,但它不会产生异常,转换成功返回 true,转换失败返回 false。最后一个参数为输出值,如果转换失败,输出值为 0

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace refout参数
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = Console.ReadLine();
            int i;
            if (int.TryParse(str ,out i))  //i在内部被赋值
            {
                Console.WriteLine("转换成功!{0}",i);
            }
            else
             { 
                Console.WriteLine("转换失败!{0}",i);
            }
            Console.ReadKey();
        }
    }
}

执行结果:

转换成功:

转换失败:

ref应用举例:
交换函数Swap:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace refout参数
{
    class Program
    {
        static void Main(string[] args)
        {
            int i1 = 10;
            int i2 = 20;
            Swap(ref i1,ref i2);  //注意ref参数
            Console.WriteLine("i1={0},i2={1}", i1, i2);
            Console.ReadKey();
        }
        static void Swap(ref int i1,ref int i2)  //注意ref参数
        {
            int temp = i1;
            i1 = i2;
            i2 = temp;
        }
    }
}

如果不使用ref参数,Swap处理的将仅仅是i1和i2的拷贝,对值本身没有影响。所以数值没有改变。

使用ref参数则将引用传入函数,而不仅是值得拷贝。

执行结果:


 

 


 

 



 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值