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 () {
}
}
结果: