Advertisement
Guest User

Untitled

a guest
Aug 20th, 2017
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.20 KB | None | 0 0
  1. public delegate void TestDelegate();
  2.  
  3. public static class ExampleOne
  4. {
  5. public static Action<string, bool> OnFunctionCall
  6. => (message, flag) => Console.WriteLine("Example");
  7. }
  8.  
  9. public static class ExampleTwo
  10. {
  11. public static TType CreateDelegate<TType>(Action<string, bool> onFunctionCall)
  12. where TType : class
  13. {
  14. var method = new DynamicMethod($"{Guid.NewGuid()}", typeof(void), Type.EmptyTypes, typeof(TType), true);
  15.  
  16. ILGenerator il = method.GetILGenerator();
  17.  
  18. // loading the first string argument
  19. il.Emit(OpCodes.Ldstr, method.Name);
  20.  
  21. // not sure here how to load boolean value to the stack
  22. il.Emit(OpCodes.Ldc_I4_0);
  23.  
  24. // this line doesn't work
  25. // example two has no idea about ExampleOne
  26. // is it possible to load the reference of the Action<string, bool> to the stack and call it ?
  27. il.Emit(OpCodes.Call, onFunctionCall.Method);
  28.  
  29. il.Emit(OpCodes.Ret);
  30.  
  31. return method.CreateDelegate(typeof(TestDelegate)) as TType;
  32. }
  33. }
  34.  
  35. public class Program
  36. {
  37. public static void Main(string[] args)
  38. => ExampleTwo
  39. .CreateDelegate<TestDelegate>(ExampleOne.OnFunctionCall)
  40. .Invoke();
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement