C#-in,ref,out

 

 看图就行

看不清:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Test : MonoBehaviour
{
  // Start is called before the first frame update
  void Start()
  {
    int a = 0, b = 1;


    Sum2(ref a, b);
    Debug.Log(string.Format("ref在传入时需要被赋值,并且这个值可以在传入后被修改,结果返回 = {0}", a));
    Sum3(out var c, b);
    Debug.Log(string.Format("out相当于函数return value,只是这个参数在内部处理时必须被赋值,相当于非void函数必须有返回值,结果返回 = {0}", c));
  }

  //1. in型参数,这个是编译无法通过的,因为in 声明的变量和readonly差不多,只读,无法修改
  //public void Sum1(in int a, int b)
  //{
    // a += b;

  //}

  //2. ref型参数
  public void Sum2(ref int a, int b)
  {
    a += b;
  }
  //3. out型参数
  public void Sum3(out int a, int b)
  {
    a = b + 2;
  }
}

猜你喜欢

转载自www.cnblogs.com/fairy-blonde/p/12011949.html