C#中可以使用out 和ref关键字, 通过引用传递参数,类型C中的指针变量
1.相同点与区别:
01.out必须在函数体内初始化,在外面初始化没意义。也就是说,out型的参数在函数体内不能得到外面传进来的初始值。
02.ref必段在函数体外初始化。
03.两都在函数体的任何修改都将影响到外面.
04.out适合用在需要retrun多个返回值的地方,而ref则用在需要被调用的方法修改调用者的引用的时候。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test : MonoBehaviour
{
string test1 = "test";
string test2; //没有初始化
void Start()
{
reffun(ref test1); //正确
Debug.Log("test1:"+test1);
reffun(ref test2); //错误,没有赋值使用了test2
Debug.Log("test2:"+test2);
outfun(out test1); //正确,但值test传进去
Debug.Log("out:"+test1);
outfun(out test2); //正确
Debug.Log("out:" + test2);
}
public void reffun(ref string str)
{
str += " fun";
}
public void outfun(out string str)
{
str = "test"; //必须在函数体内初始
str += " fun";
}
}