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

本文详细解析了C#中的ref和out参数的使用场景和区别。ref用于将变量传入函数进行处理并带回处理后的值,需在形参和实参前添加ref关键字;out用于函数返回多个不同类型值的情况,函数外部可不赋值但内部必须赋值,形参和实参需添加out关键字。

1115

被折叠的 条评论
为什么被折叠?



