리플렉션은 프로그램 실행 중 어셈블리, 타입, 메서드 등과 같은 메타데이터를 탐색하고 조작할 수 있는 기능을 제공한다. 리플렉션을 사용하면 타입에 대한 정보 뿐 아니라 객체의 속성, 메서드를 동적 호출 및 변경할 수 있다.
Type
: 객체의 타입에 대한 정보를 제공// example의 Type 객체를 습득.
Type type = typeof(example);
typeof
: 특정 타입의 System.Type
객체를 가져올 수 있다MethodInfo
: 특정 메서드에 대한 메타데이터를 제공// 타입의 메서드 정보 습득
MethodInfo methodInfo = type.GetMethod("MyMethod");
BindingFlags
private
메서드)를 검색할 때 사용public
메서드)를 검색할 때 사용GetMethods
: 타입 객체 안 메소드를 획득// 메서드 획득
MethodInfo[] methods = GetType().GetMethods(BindingFlags.Instance | BindingFlags.NonPublic);
PropertyInfo
: 클래스의 속성 정보를 제공// 타입의 속성 정보 습득
PropertyInfo propertyInfo = type.GetProperty("MyProperty");
C# 에서 델리게이트는 메서드를 참조할 수 있는 타입으로 메서드를 변수처럼 다룰 수 있게 해주는 객체이다.
이벤트 처리나 콜백 메서드를 구현할 때 매우 유용하게 사용된다.
public delegate int MyDelegate(int a, int b);
Delegate.CreateDelegate
: 리플렉션을 사용하여 특정 메서드에 대한 델리게이트를 동적으로 생성할 수 있다. 이를 통해 런타임에 메서드 참조를 동적으로 할당하고 호출할 수 있다.Action<Header> action = (Action<Header>)Delegate.CreateDelegate(typeof(Action<Header>), this, method);
위 코드는 method
에 해당하는 메서드 정보를 기반으로 Action<Header>
타입의 델리게이트를 생성한다.