[TIL] 25.02.01 SAT

GDORI·2025년 2월 2일
0

TIL

목록 보기
177/184
post-thumbnail

C# 리플렉션

리플렉션은 프로그램 실행 중 어셈블리, 타입, 메서드 등과 같은 메타데이터를 탐색하고 조작할 수 있는 기능을 제공한다. 리플렉션을 사용하면 타입에 대한 정보 뿐 아니라 객체의 속성, 메서드를 동적 호출 및 변경할 수 있다.

주요 클래스

  • Type : 객체의 타입에 대한 정보를 제공
    // example의 Type 객체를 습득.
    Type type = typeof(example);
    • typeof: 특정 타입의 System.Type 객체를 가져올 수 있다

  • MethodInfo : 특정 메서드에 대한 메타데이터를 제공
    // 타입의 메서드 정보 습득
       MethodInfo methodInfo = type.GetMethod("MyMethod");
    • BindingFlags
      - BindingFlags.Instance : 인스턴스 멤버를 검색할 때 사용
      - BindingFlags.NonPublic : 비공개 멤버(예: private 메서드)를 검색할 때 사용
      - BindingFlags.Public : 공개 멤버(예: 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

  • Delegate.CreateDelegate : 리플렉션을 사용하여 특정 메서드에 대한 델리게이트를 동적으로 생성할 수 있다. 이를 통해 런타임에 메서드 참조를 동적으로 할당하고 호출할 수 있다.
  • 예시:
    Action<Header> action = (Action<Header>)Delegate.CreateDelegate(typeof(Action<Header>), this, method);
    위 코드는 method에 해당하는 메서드 정보를 기반으로 Action<Header> 타입의 델리게이트를 생성한다.
profile
하루 최소 1시간이라도 공부하자..

0개의 댓글

관련 채용 정보