Unity3D中ref和out

ref和out 都是按地址传递的,使用后都将改变原来的数值。

别人总结的两个区别为:ref是有进有出,out是只出不进。

1.ref参数
作用:
将一个变量传入一个函数中进行"处理","处理"完成后,再将"处理"后的值带出函数。
语法:
使用时形参和实参都要添加ref关键字。
测试:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class NewBehaviourScript : MonoBehaviour {

	// Use this for initialization
	void Start () {
        int a = 1;
        int b = 2;
        refTest(ref a, b);
        Debug.Log("a:" + a + " " + "b:" + b);
	}
    private void refTest(ref int num1,int num2)
    {
        num1 = 5;
        num2 = 10;

    }
	
	// Update is called once per frame
	void Update () {
		
	}
}

结果:
在这里插入图片描述

2.out参数
作用:
一个函数中如果返回多个不同类型的值,就需要用到out参数。
语法:
函数外部可以不为变量赋值,但是函数内部必须为函数赋值。且形参和实参都要添加out关键字。
测试:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class NewBehaviourScript : MonoBehaviour {

	// Use this for initialization
	void Start () {
        int b;
        outTest(out  b);
        Debug.Log("b:" + b );
	}
    private void outTest(out int num1)
    {
        num1 = 5;
   
    }
	
	// Update is called once per frame
	void Update () {
		
	}
}

结果:
在这里插入图片描述

  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值