Guest User

Untitled

a guest
Aug 17th, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.22 KB | None | 0 0
  1. Why can I not bind a DynamicMethod to a struct instance?
  2. struct A { }
  3. ... //then some where in code::
  4. Func<Type> f = CodeGen.CreateDelegate<Func<Type>>(il=>
  5. il.ldarga_s(0)
  6. .constrained(typeof(A))
  7. .callvirt(typeof(object).GetMethod("GetType"))
  8. .ret(),
  9. name:"Constrained",
  10. target:new A()
  11. );
  12.  
  13. public static class CodeGen
  14. {
  15. public static TDelegate CreateDelegate<TDelegate>(Action<ILGenerator> genFunc, string name = "", object target = null, bool restrictedSkipVisibility = false)
  16. where TDelegate:class
  17. {
  18. ArgumentValidator.AssertGenericIsDelegateType(() => typeof(TDelegate));
  19. ArgumentValidator.AssertIsNotNull(() => genFunc);
  20.  
  21. var invokeMethod = typeof(TDelegate).GetMethod("Invoke");
  22. var @params = invokeMethod.GetParameters();
  23. var paramTypes = new Type[@params.Length + 1];
  24. paramTypes[0] = target == null ? typeof(object) : target.GetType();
  25. @params.ConvertAll(p => p.ParameterType)
  26. .CopyTo(paramTypes, 1);
  27. var method = new DynamicMethod(name ?? string.Empty, invokeMethod.ReturnType, paramTypes, restrictedSkipVisibility);
  28. genFunc(method.GetILGenerator());
  29.  
  30. return method.CreateDelegate<TDelegate>(target);
  31. }
  32. }
Add Comment
Please, Sign In to add comment