C# ref, out

m._.jooong·2023년 3월 8일
0

Unity C#

목록 보기
15/22
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

 // Value Type의 변수 : int, float, double, ..., struct(구조체)
 // Reference Type의 변수 : 배열 객체, class 객체


// ref, out : Value Type의 변수들을 Reference Type 처럼 동작시켜주는 키워드
// ref : 유연함(매개변수로 넘겨 받은 변수는 메서드안에서 사용하지 않아도 된다)
// out : 엄격함(매개변수로 넘겨 받은 변수는 메서드안에서 반드시 사용해야 한다)

public class Test_2 : MonoBehaviour
{
    void ValueMethod(int a_ii)
    {
        a_ii = 1000;
    }

    void RefMethod(ref int a_ii)
    {
        //a_ii = 1000;  // ref 키워드로 받은 매개변수는 메서드 안에서 값을 대입하지 않아도 된다.
        Debug.Log("Test" + a_ii);
    }

    void OutMethod(out int a_ii)
    {
        a_ii = 1000;    // out 키워드로 받은 매개변수는 메서드 안에서 값을 대입해 줘야 한다.
        Debug.Log("Test" + a_ii);
    }

    // Start is called before the first frame update
    void Start()
    {
        int aaa = 0;
        int bbb = aaa;
        bbb = 999;
        Debug.Log(aaa + " : " + bbb);   // 0 : 999

        int xxx = 0;
        ref int vvv = ref xxx;
        ref int yyy = ref xxx;
        ref int zzz = ref xxx;
        yyy = 999;
        Debug.Log(xxx + " : " + vvv + " : " + yyy + " : " + zzz);   /// 999 : 999: 999 : 999

        int ccc = 0;
        ValueMethod(ccc);
        Debug.Log(ccc + " : ccc");      // 0

        int ddd = 0;
        RefMethod(ref ddd);
        Debug.Log("ddd : " + ddd);      // 1000

        int eee = 0;
        OutMethod(out eee);
        Debug.Log("eee : " + eee);      // 1000

        string a_mm = "123.456";
        float a_pp = 0.0f;
        bool IsOk = float.TryParse(a_mm, out a_pp);
        Debug.Log("a_pp : " + a_pp);

    }//void Start()

    // Update is called once per frame
    void Update()
    {
        
    }
}

0개의 댓글