1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
| namespace ConsoleApp1 { using System; using System.Reflection; using System.Reflection.Emit;
public class Example { private static object timer;
public static void Main() { Type t = typeof(System.Timers.Timer); timer = Activator.CreateInstance(t);
EventInfo eInfo = t.GetEvent("Elapsed");
Type handlerType = eInfo.EventHandlerType; MethodInfo invokeMethod = handlerType.GetMethod("Invoke"); ParameterInfo[] parms = invokeMethod.GetParameters(); Type[] parmTypes = new Type[parms.Length]; for (int i = 0; i < parms.Length; i++) { parmTypes[i] = parms[i].ParameterType; }
AssemblyName aName = new AssemblyName(); aName.Name = "DynamicTypes"; AssemblyBuilder ab = AssemblyBuilder.DefineDynamicAssembly(aName, AssemblyBuilderAccess.Run); ModuleBuilder mb = ab.DefineDynamicModule(aName.Name); TypeBuilder tb = mb.DefineType("Handler", TypeAttributes.Class | TypeAttributes.Public);
MethodBuilder handler = tb.DefineMethod("DynamicHandler", MethodAttributes.Public | MethodAttributes.Static, invokeMethod.ReturnType, parmTypes);
ILGenerator il = handler.GetILGenerator(); il.EmitWriteLine("Timer's Elapsed event is raised."); il.Emit(OpCodes.Ret);
Type finished = tb.CreateType(); MethodInfo eventHandler = finished.GetMethod("DynamicHandler");
Delegate d = Delegate.CreateDelegate(handlerType, eventHandler); eInfo.AddEventHandler(timer, d);
t.InvokeMember("Interval", BindingFlags.SetProperty, null, timer, new Object[] { 1000 }); t.InvokeMember("Enabled", BindingFlags.SetProperty, null, timer, new Object[] { true });
Console.WriteLine("Press the Enter key to end the program."); Console.ReadLine(); } } }
|