C# - 실행 시점에 동적으로 Delegate 타입을 만드는 방법
예를 들어, 다음과 같이 delegate 타입을 만들 수 있는데요,
using System;
public delegate void ActionDelegate(object obj);
class Program
{
static void Main(string[] args)
{
Console.WriteLine(typeof(ActionDelegate).FullName);
}
}
C#의
delegate 예약어 덕분에 ActionDelegate가 단순히 선언문 정도로 여겨질 수 있지만, C# 컴파일러는 내부적으로 이를 확장해 System.MulticastDelegate 타입을 상속받는 타입으로 정의를 합니다.
그래서, 실행 시(runtime)에 delegate 타입을 만들고 싶다면 C# 문법에서 지원하는 약식 코드인 "public delegate void ActionDelegate(object obj);" 방식으로는 불가능하고 실제 타입을 만드는 과정 그대로 진행을 해야 합니다. 이와 관련해서 다음의 repo에 delegate 타입을 만드는 코드를 찾을 수 있습니다.
Phalanger/Source/Core/Emit/DelegateBuilder.cs /
; https://github.com/DEVSENSE/Phalanger/blob/master/Source/Core/Emit/DelegateBuilder.cs
위의 소스 코드를 추려 다음과 같이 ActionDelegate와 같은 형식의 타입을 새로 만들 수 있습니다.
AssemblyName myAssemblyName = new AssemblyName();
myAssemblyName.Name = "EmittedAssembly_" + Guid.NewGuid().ToString();
AssemblyBuilder myAssembly = AppDomain.CurrentDomain.DefineDynamicAssembly(myAssemblyName,
AssemblyBuilderAccess.Run);
ModuleBuilder moduleBuilder = myAssembly.DefineDynamicModule("EmittedModule");
Type myActionDelegate2 = CreateDelegateType(moduleBuilder, new Type[] { typeof(object), typeof(void) }, "MyActionDelegate");
Console.WriteLine(myActionDelegate2.FullName); // 출력 결과 MyActionDelegate
public static readonly Type[] DelegateCtorSignature = new Type[] { typeof(object), typeof(IntPtr) };
private static Type CreateDelegateType(ModuleBuilder moduleBuilder, Type[] types, string delegateTypeName)
{
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();
}
좀 코드가 많죠? ^^ 위와는 다르지만, 결국 같은 delegate 타입을 만드는 방법이
Expression.GetDelegateType으로 제공이 됩니다. 따라서 이를 활용하면 다음과 같이 간단하게 델리게이트 타입을 동적으로 만들 수 있습니다.
Type myActionDelegate3 = Expression.GetDelegateType(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]]
*/
보는 바와 같이 Expression.GetDelegateType의 경우, 타입을 새로 만드는 것은 아니고 System.Action에 묻어가는 형식으로 델리게이트 타입을 반환합니다.
(
첨부 파일은 이 글의 예제 코드를 포함합니다.)
[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]