[C#] 30. 리플렉션(Reflection)

Connected Brain·2025년 4월 25일

면접 질문 대비

목록 보기
30/60

리플렉션(Reflection)이 뭔지, 사용을 해봤다면 어떤 이유에서 사용했는지 설명해주세요.

한줄 요약

리플렉션은 런타임(코드 실행 중)에 객체의 타입 정보를 확인하고, 해당 객체의 속성이나 메서드를 동적으로 접근하거나 호출할 수 있게 해주는 C# 기능입니다.

리플렉션(Reflection)

  • 리플랙션은 프로그램이 런타임 중에 객체의 구조를 확인할 수 있도록 하는 기능
  • 리플랙션을 이용해 어떤 형식인지 확인하거나, 속성을 가져와 값을 입력하는 등의 기능을 수행할 수 있음
  • 타입의 이름을 문자열로만 알고 있을 때 이를 실제 타입으로 가져오거나, 메서드를 실행하는 목적으로 사용할 수 있음
  • 그러나 리플랙션을 활용하는 것은 성능 상에 부담을 주므로 자주 실행하지 않거나, 초기 실행시 초기화 작업에 사용하는 것이 권장됨

사용 예시 1

public class InstanceDataBase<T> where T : BaseData
{
    static Dictionary<int, Tuple<Type, T>> instanceDictionary;

    public static void Initialize()
    {
        if(instanceDictionary != null) return;
        
        Assembly assembly = Assembly.GetExecutingAssembly();
        instanceDictionary = new Dictionary<int, Tuple<Type, T>>();
        
        var instanceDataBases = Resources.LoadAll<T>(GetResourcePath<T>());
        foreach (var instance in instanceDataBases)
        {
            Type currentInstanceType = assembly.GetType(instance.name + GetTypeName<T>());
            instanceDictionary.Add(instance.index, new Tuple<Type, T>(currentInstanceType, instance));
            //Debug.Log($"{instance.index} : {currentInstanceType.Name}, {instance.name}");
        }
        
        Debug.Log(GetTypeName<T>()+" Initialized");
    }
    
    ...
}
  • Unity 프로젝트에서 특정 경로에 있는 Scriptable Object 파일을 가져와, 해당 파일이 가지고 있는 이름 정보와, generic T를 통해 입력한 형식 정보를 비교해 그에 맞는 type과 해당 스크립터블 오브젝트 데이터를 instanceDictionary에 저장해, 향후 런타임에서 해당 type에 해당하는 생성자를 찾을 수 있도록 하는 기능을 구현하는데 사용

사용 예시 2

public void GetDatas(SheetData sheet)
    {
        foreach (var data in sheet.datas)
        {
            var path = sheet.OutPath + "/" + data[instance.fileNameElement] + ".asset";
            
            Assembly assembly = typeof(BaseData).Assembly;
            Debug.Log(data[instance.classNameElement]);
            var type = assembly.GetType(data[instance.classNameElement]);
            Debug.Log(type.Name);
            
            var dt = (ScriptableObject)AssetDatabase.LoadAssetAtPath(path, type);
            if (dt == null)
            {
                Debug.Log("type : " + type);
                dt = DicToClass(type, data, sheet.OutPath);
            }
            else
            {
                Debug.Log("type : " + type);
                dt = TSVParser.DicToSOData(type, dt, data);
            }

            EditorUtility.SetDirty(dt);
            AssetDatabase.SaveAssets();
        }
    }
  • 구글 시트에서 정보를 가져와 스크립터블 오브젝트로 저장하는 함수에서, 구글 시트에 포함된 클래스 이름 정보 classNameElement에 따라 스크립터블 오브젝트를 생성해 저장하도록하는데 리플랙션을 활용함

0개의 댓글