ref和out提供了值类型按引用进行传递的解决方案。
1.ref作为参数的函数在调用前,实参必须赋初始值。
2.out作为参数的函数在调用前,实参可以不赋初始值。
3.在被调用函数内,out引入的参数在返回前至少赋值一次
void Awake() //
{
int a = 1 ;
int b = 2 ;
Debug.Log(string.Format("交换前\ta={0}\tb={1}\t", a, b));
Swap( a, b);
Debug.Log(string.Format("交换后\ta={0}\tb={1}\t", a, b));
} //交换a,b两个变量的值
private static void Swap( int a, int b)
{
int temp = a;
a = b;
b = temp;
Debug.Log(string.Format("方法内\ta={0}\tb={1}\t", a, b));
}
void Awake()
{
int a = 1 ;
int b = 2 ;
Debug.Log(string.Format("交换前\ta={0}\tb={1}\t", a, b));
Swap( ref a, ref b);
Debug.Log(string.Format("交换后\ta={0}\tb={1}\t", a, b));
} //交换a,b两个变量的值
private static void Swap(ref int a, ref int b)
{
int temp = a;
a = b;
b = temp;
Debug.Log(string.Format("方法内\ta={0}\tb={1}\t", a, b));
}
学习链接
备忘