본문 바로가기

C#

리플렉션

런타임 시점에 처리 가능.

컴파일 시점에 처리되는 것들 런타임 시점엔 모르니까.. 런타임 시점에서 리플렉션 써서 어거지로 갖고 오는거

나중에 이런게 생길거니까 미리 세팅 해놓으라고 위임하는 느낌인듯

 

using System.Reflection 추가 필수

 

 

type.GetFields 멤버 변수 가져오기
type.GetPropertys 멤버 프로퍼티 가져오기

MethodInfo[] methods = type.GetMethods();   //멤버 함수 가져옴

 

 

 

GetComponent("이름")

문자열은 바꾸기 쉬우니까..

 

 

 

ex) Debug.Log(type.GetField("tempValue"), GetValue(tempA));

누구한테서 어떤 값을 가져올 것이냐.

 

 

 

Type type = tempA.GetType();  type에 담기는것은 tempA의 클래스 정보이지 tempA가 아니다.

 

 

 

 

Debug.Log(type.GetField("tempValue").GetValue(tempA)); 

type.GetField("tempValue").SetValue(tempA,30);
Debug.Log(type.GetField("tempValue").GetValue(tempA));

 

tempA의 값 바뀌어서 나옴

 

 

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


public class Slime
{
    public int hp;
    public int atk;

    public int Hp
    {
        get { return hp; }
        set { hp = value; }
    }

    public void Attack()
    {
        Debug.Log("슬라임이"+atk+"만큼 때림");
    }
}

public class Reflection : MonoBehaviour
{
    //리플렉션 : 타입에 대한 정보를 담는 메타적인 문법

    void Start()
    {
        Slime slimeA = new Slime();
        slimeA.hp = 100;
        Slime slimeB = new Slime();
        slimeB.hp = 50;

        Debug.Log(slimeA.GetType());    //클래스의 이름인 Slime이 나옴
        Debug.Log(slimeB.GetType());    //클래스의 이름인 Slime이 나옴

        Type type = slimeA.GetType();    //Slime클래스의 정보를 받아오고싶은것이기때문에
        type = slimeB.GetType();         //slimeA의 타입이던 slimeB의 타입이던 상관없음

        FieldInfo[] fields =  type.GetFields(); //멤버 변수 전체를 가져오는 함수
        foreach(FieldInfo field in fields)
        {
            Debug.Log(field.Name);
        }
        type.GetField("atk").SetValue(slimeA, 150);
        //type에 담긴 Slime클래스의 멤버변수 atk를 가져와서 150으로 셋팅해준다. 대상은 slimeA객체에게
        type.GetField("atk").SetValue(slimeB, 350);
        type.GetMethod("Attack").Invoke(slimeA, null);
        //type에 담긴 Slime클래스의 멤버함수 Attack을 가져와서 실행한다 누구의? slimeA의
        type.GetMethod("Attack").Invoke(slimeB, null);
    }
}

 

단점: 연산이 큼.. string으로 안에 있는 멤버들 쫙 검색한단거니까.

남용하면 최적화에 방해가 됨.

'C#' 카테고리의 다른 글

Deep Copy  (0) 2022.06.22
Parameter / Arguments 차이  (0) 2022.06.22
template method  (0) 2022.06.21
EventHandler  (0) 2022.06.21
프로퍼티  (0) 2022.06.21