Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일

(시리즈 글이 11개 있습니다.)
.NET Framework: 404. 리플렉션을 이용해 닷넷 LicenseManager를 우회할 수 있는 사례
; https://www.sysnet.pe.kr/2/0/1565

.NET Framework: 428. .NET Reflection으로 다차원/Jagged 배열을 구분하는 방법
; https://www.sysnet.pe.kr/2/0/1653

.NET Framework: 537. C# - Reflection의 박싱 없이 값 형식을 다루는 방법
; https://www.sysnet.pe.kr/2/0/10866

.NET Framework: 685. C# - 구조체(값 형식)의 필드를 리플렉션을 이용해 값을 바꾸는 방법
; https://www.sysnet.pe.kr/2/0/11312

.NET Framework: 785. public으로 노출되지 않은 다른 어셈블리의 delegate 인스턴스를 Reflection으로 생성하는 방법
; https://www.sysnet.pe.kr/2/0/11583

.NET Framework: 842. .NET Reflection을 대체할 System.Reflection.Metadata 소개
; https://www.sysnet.pe.kr/2/0/11930

.NET Framework: 924. C# - Reflection으로 변경할 수 없는 readonly 정적 필드
; https://www.sysnet.pe.kr/2/0/12256

.NET Framework: 1045. C# - 런타임 시점에 이벤트 핸들러를 만들어 Reflection을 이용해 구독하는 방법
; https://www.sysnet.pe.kr/2/0/12609

.NET Framework: 1046. C# - 컴파일 시점에 참조할 수 없는 타입을 포함한 이벤트 핸들러를 Reflection을 이용해 구독하는 방법
; https://www.sysnet.pe.kr/2/0/12610

닷넷: 2155. C# - .NET 8 런타임부터 (Reflection 없이) 특성을 이용해 public이 아닌 멤버 호출 가능
; https://www.sysnet.pe.kr/2/0/13436

닷넷: 2249. C# - 부모의 필드/프로퍼티에 대해 서로 다른 자식 클래스 간에 Reflection 접근이 동작할까요?
; https://www.sysnet.pe.kr/2/0/13608




C# - 런타임 시점에 이벤트 핸들러를 만들어 Reflection을 이용해 구독하는 방법

간단하게 이벤트 하나를 제공하는 타입을 만들어,

public class TempEventArgs : EventArgs
{
    public string Name;
}

public class MyTemp
{
    public void Create()
    {
        Created(this, new TempEventArgs { Name = "MyTEmp" });
    }

    public event EventHandler<TempEventArgs> Created;
}

Reflection을 이용하면 다음과 같이 이벤트 핸들러를 Reflection으로 추가할 수 있습니다.

using System;
using System.Reflection;

class Program
{
    static void Main(string[] args)
    {
        MyTemp instance = new MyTemp();
        MyTempEventTest(instance);

        instance.Create();
    }

    private static void Instance_Created(object sender, TempEventArgs e)
    {
        Console.WriteLine("Event Fired: " + e.Name);
    }

    private static void MyTempEventTest(object objTarget)
    {
        EventInfo ei = typeof(MyTemp).GetEvent("Created", BindingFlags.Public | BindingFlags.Instance);
        ei.AddEventHandler(objTarget, (EventHandler<TempEventArgs>)Instance_Created);
    }
}




여기까지만 하면 재미가 없으니, 상황을 좀 꼬아서 이벤트 핸들러까지 동적으로 런타임에 만들어 구독을 추가해 보겠습니다. 사실 이렇게까지 만들 일은 거의 없지만 그래도 DynamicMethod의 예제로써,

How to: Define and Execute Dynamic Methods
; https://learn.microsoft.com/en-us/dotnet/framework/reflection-and-codedom/how-to-define-and-execute-dynamic-methods

나름 괜찮으니 ^^ 이를 이용해 다음과 같이 IL 코드를 직접 추가해 이벤트 핸들러를 동적으로 만들 수 있습니다.

static void Main(string[] args)
{
    MyTemp instance = new MyTemp();

    SubscribeAtRuntime(instance);

    instance.Create();
}

private static void SubscribeAtRuntime(MyTemp instance)
{
    Type targetType = instance.GetType();
        
    EventInfo ei = targetType.GetEvent("Created", BindingFlags.Public | BindingFlags.Instance);
    MethodInfo consoleWriteMethod = typeof(Console).GetMethod("Write", BindingFlags.Public | BindingFlags.Static, null, new Type [] { typeof(object) }, null);
    MethodInfo consoleWriteLineMethod = typeof(Console).GetMethod("WriteLine", BindingFlags.Public | BindingFlags.Static, null, new Type[] { typeof(object) }, null);
    FieldInfo nameField = typeof(TempEventArgs).GetField("Name", BindingFlags.Public | BindingFlags.Instance);

    DynamicMethod proxyMethod = new DynamicMethod(
        "Proxy_Created",
        typeof(void), new Type[] { typeof(object), typeof(TempEventArgs) });

    ILGenerator il = proxyMethod.GetILGenerator();

    // Console.Write("Event Fired: " );
    il.Emit(OpCodes.Ldstr, "Event Fired: ");
    il.Emit(OpCodes.Call, consoleWriteMethod);

    // Console.WriteLine(e.Name);
    il.Emit(OpCodes.Ldarg_1);
    il.Emit(OpCodes.Ldfld, nameField);
    il.Emit(OpCodes.Call, consoleWriteLineMethod);
    il.Emit(OpCodes.Ret);

    Type eventHandlerType = typeof(EventHandler<TempEventArgs>);
    Delegate proxyDelegate = proxyMethod.CreateDelegate(eventHandlerType);

    ei.AddEventHandler(instance, proxyDelegate);
}

위에서 DynamicMethod.CreateDelegate 메서드에,

DynamicMethod.CreateDelegate Method
; https://learn.microsoft.com/en-us/dotnet/api/system.reflection.emit.dynamicmethod.createdelegate

전달한 타입은 "System.EventHandler`1[TempEventArgs]"입니다. 그리고 이 타입은 EventInfo 인스턴스를 통해서도 구할 수 있는데, 따라서 다음과 같이 전달하는 것도 가능합니다.

Delegate proxyDelegate = proxyMethod.CreateDelegate(ei.EventHandlerType);
ei.AddEventHandler(instance, proxyDelegate);

(첨부 파일은 이 글의 예제 코드를 포함합니다.)




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 11/7/2023]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 46  47  48  49  50  51  52  53  [54]  55  56  57  58  59  60  ...
NoWriterDateCnt.TitleFile(s)
12292정성태8/20/202012408.NET Framework: 932. C# - ETW 관련 Win32 API 사용 예제 코드 (1)파일 다운로드2
12291정성태8/15/202011385오류 유형: 638. error 1297: Device driver does not install on any devices, use primitive driver if this is intended.
12290정성태8/11/202012033.NET Framework: 931. C# - IP 주소에 따른 국가별 위치 확인 [8]파일 다운로드1
12289정성태8/6/20209503개발 환경 구성: 502. Portainer에 윈도우 컨테이너를 등록하는 방법
12288정성태8/5/20209568오류 유형: 637. WCF - The protocol 'net.tcp' does not have an implementation of HostedTransportConfiguration type registered.
12287정성태8/5/202010035오류 유형: 636. C# - libdl.so를 DllImport로 연결 시 docker container 내에서 System.DllNotFoundException 예외 발생
12286정성태8/5/202010834개발 환경 구성: 501. .NET Core 용 container 이미지 만들 때 unzip이 필요한 경우
12285정성태8/4/202011235오류 유형: 635. 윈도우 10 업데이트 - 0xc1900209 [2]
12284정성태8/4/202010516디버깅 기술: 169. Hyper-V의 VM에 대한 메모리 덤프를 뜨는 방법
12283정성태8/3/202010992디버깅 기술: 168. windbg - 필터 드라이버 확인하는 확장 명령어(!fltkd) [2]
12282정성태8/2/20209716디버깅 기술: 167. windbg 디버깅 사례: AppDomain 간의 static 변수 사용으로 인한 crash (2)
12281정성태8/2/202012293개발 환경 구성: 500. (PDB 연결이 없는) DLL의 소스 코드 디버깅을 dotPeek 도구로 해결하는 방법
12280정성태8/2/202011451오류 유형: 634. 오라클 (평생) 무료 클라우드 VM 생성 후 SSH 접속 시 키 오류 발생 [2]
12279정성태7/29/202012343개발 환경 구성: 499. 닷넷에서 접근해보는 InterSystems의 Cache 데이터베이스파일 다운로드1
12278정성태7/23/20209603VS.NET IDE: 149. ("Binary was not built with debug information" 상태로) 소스 코드 디버깅이 안되는 경우
12277정성태7/23/202011122개발 환경 구성: 498. DEVPATH 환경 변수의 사용 예 - .NET Reflector의 (PDB 연결이 없는) DLL의 소스 코드 디버깅
12276정성태7/23/202010426.NET Framework: 930. 개발자를 위한 닷넷 어셈블리 바인딩 - DEVPATH 환경 변수
12275정성태7/22/202012907개발 환경 구성: 497. 닷넷에서 접근해보는 InterSystems의 IRIS Data Platform 데이터베이스파일 다운로드1
12274정성태7/21/202012302개발 환경 구성: 496. Azure - Blob Storage Account의 Location 이전 방법 [1]파일 다운로드1
12273정성태7/18/202013982개발 환경 구성: 495. Azure - Location이 다른 웹/DB 서버의 경우 발생하는 성능 하락
12272정성태7/16/20208914.NET Framework: 929. (StrongName의 버전 구분이 필요 없는) .NET Core 어셈블리 바인딩 규칙 [2]파일 다운로드1
12271정성태7/16/202010998.NET Framework: 928. .NET Framework의 Strong-named 어셈블리 바인딩 (2) - 런타임에 바인딩 리디렉션파일 다운로드1
12270정성태7/16/202011770오류 유형: 633. SSL_CTX_use_certificate_file - error:140AB18F:SSL routines:SSL_CTX_use_certificate:ee key too small
12269정성태7/16/20208722오류 유형: 632. .NET Core 웹 응용 프로그램 - The process was terminated due to an unhandled exception.
12268정성태7/15/202010931오류 유형: 631. .NET Core 웹 응용 프로그램 오류 - HTTP Error 500.35 - ANCM Multiple In-Process Applications in same Process
12267정성태7/15/202012548.NET Framework: 927. C# - 윈도우 프로그램에서 Credential Manager를 이용한 보안 정보 저장파일 다운로드1
... 46  47  48  49  50  51  52  53  [54]  55  56  57  58  59  60  ...