성태의 닷넷 이야기
홈 주인
모아 놓은 자료
프로그래밍
질문/답변
사용자 관리
사용자
메뉴
아티클
외부 아티클
유용한 코드
온라인 기능
MathJax 입력기
최근 덧글
[정성태] Get Started with Milvus Vector DB i...
[정성태] cyberark/PipeViewer - A tool that...
[정성태] WinForms in a 64-Bit world – our st...
[정성태] 예제에서 SELECT_SQL도 내부적으로는 SqlCommand/...
[victor] SELECT_LINQ SELECT_SQL 같은 쿼리인...
[victor] 답변 갑사합니다. 예외(Exception)가 났습니다. ...
[정성태] 일단, 위의 방식대로 하면 예외(Exception) 없이 잘 동...
[정성태] Windows 10 (버전 1809)에 이런 기능이 ^^ 추가되...
[정성태] pde windbg extension ; https://lea...
[정성태] // GetEnumerator extensions for Ran...
글쓰기
제목
이름
암호
전자우편
HTML
홈페이지
유형
제니퍼 .NET
닷넷
COM 개체 관련
스크립트
VC++
VS.NET IDE
Windows
Team Foundation Server
디버깅 기술
오류 유형
개발 환경 구성
웹
기타
Linux
Java
DDK
Math
Phone
Graphics
사물인터넷
부모글 보이기/감추기
내용
<div style='display: inline'> <h1 style='font-family: Malgun Gothic, Consolas; font-size: 20pt; color: #006699; text-align: center; font-weight: bold'>C# - 실행 시점에 동적으로 Delegate 타입을 만드는 방법</h1> <p> 예를 들어, 다음과 같이 delegate 타입을 만들 수 있는데요,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > using System; <span style='color: blue; font-weight: bold'>public delegate void ActionDelegate(object obj);</span> class Program { static void Main(string[] args) { Console.WriteLine(typeof(ActionDelegate).FullName); } } </pre> <br /> C#의 <a target='tab' href='https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/delegates/'>delegate 예약어</a> 덕분에 ActionDelegate가 단순히 선언문 정도로 여겨질 수 있지만, C# 컴파일러는 내부적으로 이를 확장해 System.MulticastDelegate 타입을 상속받는 타입으로 정의를 합니다.<br /> <br /> 그래서, 실행 시(runtime)에 delegate 타입을 만들고 싶다면 C# 문법에서 지원하는 약식 코드인 "public delegate void ActionDelegate(object obj);" 방식으로는 불가능하고 실제 타입을 만드는 과정 그대로 진행을 해야 합니다. 이와 관련해서 다음의 repo에 delegate 타입을 만드는 코드를 찾을 수 있습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > Phalanger/Source/Core/Emit/DelegateBuilder.cs / ; <a target='tab' href='https://github.com/DEVSENSE/Phalanger/blob/master/Source/Core/Emit/DelegateBuilder.cs'>https://github.com/DEVSENSE/Phalanger/blob/master/Source/Core/Emit/DelegateBuilder.cs</a> </pre> <br /> 위의 소스 코드를 추려 다음과 같이 ActionDelegate와 같은 형식의 타입을 새로 만들 수 있습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > AssemblyName myAssemblyName = new AssemblyName(); myAssemblyName.Name = "EmittedAssembly_" + Guid.NewGuid().ToString(); AssemblyBuilder myAssembly = AppDomain.CurrentDomain.DefineDynamicAssembly(myAssemblyName, AssemblyBuilderAccess.Run); ModuleBuilder moduleBuilder = myAssembly.DefineDynamicModule("EmittedModule"); <span style='color: blue; font-weight: bold'>Type myActionDelegate2 = CreateDelegateType(moduleBuilder, new Type[] { typeof(object), typeof(void) }, "MyActionDelegate");</span> Console.WriteLine(myActionDelegate2.FullName); // 출력 결과 MyActionDelegate public static readonly Type[] DelegateCtorSignature = new Type[] { typeof(object), typeof(IntPtr) }; <span style='color: blue; font-weight: bold'>private static Type CreateDelegateType(ModuleBuilder moduleBuilder, Type[] types, string delegateTypeName)</span> { TypeBuilder typeBuilder = moduleBuilder.DefineType(delegateTypeName, TypeAttributes.Public | TypeAttributes.Sealed | TypeAttributes.AutoClass, typeof(MulticastDelegate)); Type returnType = types[types.Length - 1]; Type[] parameterTypes = types.Take(types.Length - 1).ToArray(); // Array.RemoveLast<Type>(types); typeBuilder.DefineConstructor(MethodAttributes.FamANDAssem | MethodAttributes.Family | MethodAttributes.HideBySig | MethodAttributes.RTSpecialName, CallingConventions.Standard, DelegateCtorSignature).SetImplementationFlags(MethodImplAttributes.CodeTypeMask); typeBuilder.DefineMethod("Invoke", MethodAttributes.FamANDAssem | MethodAttributes.Family | MethodAttributes.Virtual | MethodAttributes.HideBySig | MethodAttributes.VtableLayoutMask, returnType, parameterTypes).SetImplementationFlags(MethodImplAttributes.CodeTypeMask); return typeBuilder.CreateType(); } </pre> <br /> 좀 코드가 많죠? ^^ 위와는 다르지만, 결국 같은 delegate 타입을 만드는 방법이 <a target='tab' href='https://docs.microsoft.com/en-us/dotnet/api/system.linq.expressions.expression.getdelegatetype'>Expression.GetDelegateType</a>으로 제공이 됩니다. 따라서 이를 활용하면 다음과 같이 간단하게 델리게이트 타입을 동적으로 만들 수 있습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > Type myActionDelegate3 = <span style='color: blue; font-weight: bold'>Expression.GetDelegateType</span>(new Type[] { typeof(object), typeof(void) }); Console.WriteLine(myActionDelegate3.FullName); /* 출력 결과 System.Action`1[[System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] */ </pre> <br /> 보는 바와 같이 Expression.GetDelegateType의 경우, 타입을 새로 만드는 것은 아니고 System.Action에 묻어가는 형식으로 델리게이트 타입을 반환합니다.<br /> <br /> (<a target='tab' href='https://www.sysnet.pe.kr/bbs/DownloadAttachment.aspx?fid=1747&boardid=331301885'>첨부 파일은 이 글의 예제 코드를 포함</a>합니다.)<br /> </p><br /> <br /><hr /><span style='color: Maroon'>[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]</span> </div>
첨부파일
스팸 방지용 인증 번호
1175
(왼쪽의 숫자를 입력해야 합니다.)