C# 복습하기 15) 리플렉션

리플렉션 

msdn : 리플렉션(C#)
https://docs.microsoft.com/ko-kr/dotnet/csharp/programming-guide/concepts/reflection

 - 객체의 형식 정보를 들여다보는 기능.

 - 프로그램 실행 중 동적으로 형식 인스턴스를 만들거나, 형식을 기존 개체에 바인딩하거나, 기존 개체에서 형식을 가져와 해당 메서드를 호출하거나, 필드 및 속성에 액세스 할 수 있는 기능을 제공한다.

 

Object.GetType() 메서드와

 - Object클래스는 GetType() 메서드를 가지고 있다.

int i = 42;
Type type = i.GetType();
Console.WriteLine(type);

 

Type클래스

msdn : Type클래스
docs.microsoft.com/ko-kr/dotnet/api/system.type?redirectedfrom=MSDN&view=net-5.0

 - Type 형식은 단순히 형식 이름뿐만 아니라 소속 어셈블리 이름, 프로퍼티 목록, 메서드 목록, 필드 목록, 이벤트 목록 등의 정보를 담고 있다.

FieldInfo[] fields = type.GetFields();

foreach(FieldInfo field in fields)
    Console.WriteLine("Type:{0}, Name:{1}, fieldType.Name, field.Name");

 - Type 클래스가 가지고 있는 대표적 메서드 목록

메소드 반환 형식 설명
GetConstructors() ConstructorInfo[] 생성자 목록을 반환
GetEvents() EventInfo[] 이벤트 목록을 반환
GetFields() FieldInfo[] 필드 목록을 반환
GetGenericArguments() Type[] 형식 매개 변수 목록을 반환
GetInterfaces() Type[] 상속하는 인터페이스 목록을 반환
GetMembers() MemberInfo[] 멤버 목록을 반환
GetMethods() MethodInfo[] 메소드 목록을 반환
GetNestedTypes() Type[] 내장 형식 목록을 반환
GetProperties() PropertyInfo[] 프로퍼티 목록을 반환

 - GetFields()나 GetMethods() 등은 플래그를 사용하여 public, Instance, static 항목들만 조회하는 것도 가능하다. 

var fields = type.GetFields(BindingsFlags.Public | BindingsFlags.Instance);

 

typeof연산자

 - Object.GetType()은 인스턴스에서 타입을 받아오지만, typeof는 형식 식별자 자체를 매개변수로 타입을 받을 수 있다.

Type type = typeof(int);

 

리플렉션으로 객체 생성하기

 - System.Activator를 사용하여 형식으로 인스턴스를 생성할 수 있다.

object a = Activator.CreateInstance(typeof(int));
List<int> b = Activator.CreateInstance<List<int>>();

 

프로퍼티 할당하기

 - PropertyInfo.SetValue() 메서드를 이용하여 동적으로 프로퍼티를 할당할 수 있다.

class MyClass
{
    public string Name{get;set;}
}

static void Main()
{
    Type type = typeof(MyClass);
    Object obj = Activator.CreateInstance(type);
    
    PropertyInfo name = type.GetProperty("Name");
    name.SetValue(obj, "이름", null); // 세번째 매개변수는 인덱서의 인덱스를 의미함
    
    Console.WriteLine(name.GetValue(obj, null));  // 두번째 매개변수는 인덱서의 인덱스를 의미함
}

 

MethodInfo 클래스에서 메서드 호출하기

 - Invoke()를 사용하여 메서드를 호출할 수도 있다.

class MyClass
{
    public string Name{get;set;}
    public void MyMethod()
    {
        //..
    }
}

static void Main()
{
    Type type = typeof(MyClass);
    MyClass myClass = (MyClass)Activator.CreateInstance(type);
    myClass.Name = "이름";
    
    MethodInfo method = type.GetMethod("MyMethod");
    method.Invoke(myClass, null); // 두번째 인자는 메서드의 매개변수
}

 

형식 내보내기

 - System.Reflection.Emit 네임 스페이스에 있는 클래스들을 통해 새로운 형식을 만들어 낼 수도 있다.

 

 

 

 

 

 

'C# Study > C# 기초' 카테고리의 다른 글

C# 복습하기 17) dynamic 형식  (0) 2021.04.15
C# 복습하기 16) 애트리뷰트(Attribute)  (0) 2021.04.14
C# 복습하기 14) LINQ  (0) 2021.04.13
C# 복습하기 13) 람다식  (0) 2021.04.13
C# 복습하기 12) 대리자와 이벤트  (0) 2021.04.12

댓글

Designed by JB FACTORY