ref与out

注意点:

  • ref和out都是按地址传递,使用后都将改变原来参数的数值
  • 方法定义和调用方法都必须显式使用 ref/out 关键字

ref:

  • 作为ref参数传递的变量在方法调用中传递之前必须初始化

out:

  • 作为 out 参数传递的变量在方法调用中传递之前不必初始化
  • 被调用的方法需要在返回之前赋一个值
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Test : MonoBehaviour {
    void Start () {
        int a=1;//必须初始化
        int b=3;//必须初始化
        handlerRef(ref a,ref b);
        Debug.LogFormat("a:{0} b:{1}",a,b);//output: a:4 b:2

        int c;//不必初始化
        int d;//不必初始化
        handlerOut(out c,out d);
        Debug.LogFormat("c:{0} d:{1}",c,d);//output: c:5 d:6
    }

    private void handlerRef(ref int a, ref int b){
        a=a+b;
        b=2;
    }

    private void handlerOut(out int c,out int d){
        c=5;//必须对c赋值
        d=c+1;//必须对d赋值
    }
}
原文地址:https://www.cnblogs.com/kingBook/p/8383888.html