using System.Diagnostics.Contracts; using System.Linq; using System.Threading; namespace System.Reflection.Emit { /// /// A that can be used to easily (lol) create dynamic methods /// /// The type of that will be used to wrap the new methods internal static class DynamicMethod where T : Delegate { /// /// The owner type for new dynamic methods /// private static readonly Type OwnerType = typeof(DynamicMethod); /// /// The return type of the /// private static readonly Type ReturnType; /// /// The types of the arguments of the /// private static readonly Type[] ParameterTypes; /// /// Loads all the necessary info for the current parameter /// static DynamicMethod() { MethodInfo method = typeof(T).GetMethod("Invoke")!; ReturnType = method.ReturnType; ParameterTypes = method.GetParameters().Select(p => p.ParameterType).ToArray(); } /// /// Local counter for dynamic methods of type ever generated /// private static int _Count; /// /// Creates a new for the target owner /// /// An that builds the IL bytecode for the new method /// A new dynamic method wrapped as a [Pure] public static T New(Action builder) { // Create a new dynamic method with a unique id string id = $"__IL__{typeof(T).Name}_{Interlocked.Increment(ref _Count)}"; DynamicMethod method = new DynamicMethod(id, ReturnType, ParameterTypes, OwnerType); // Build the IL bytecode ILGenerator il = method.GetILGenerator(); builder(il); // Build and delegate instance return (T)method.CreateDelegate(typeof(T)); } } }