Create a new method with a user-defined name. C # reflection

I want to create a method in RunTime. I want the user to enter a string, and the method name is DynamicallyDefonedMethod _ #### (ends with a user string).

I want the same line to be embedded in the body of the method: It will call StaticDefinedMethod (####, a, b)

Sort of:

public MyClass1 DynamicallyDefonedMethod_#### (int a, int b)
{
return  StaticallyDefinedMethod (####, a, b)
}

The idea is that the user creates a new method at runtime and calls it after (with parameters a, b).

i googled C # reflection but did not find an easy way to do this. Does anyone know how to do this simply?

Hi,

+3
source share
1 answer

As already noted (comments), a simpler approach is to use lambda:

Func<int,int,Whatever> func = (a,b) => StaticallyDefinedMethod(s,a,b);

(). ( , ). , - . .

using System;
using System.Reflection.Emit;
public class MyClass1  {
    static void Main()
    {
        var foo = CreateMethod("Foo");
        string s = foo(123, 456);
        Console.WriteLine(s);
    }
    static Func<int,int,string> CreateMethod(string s)
    {
        var method = new DynamicMethod("DynamicallyDefonedMethod_" + s,
            typeof(string),
            new Type[] { typeof(int), typeof(int) });
        var il = method.GetILGenerator();
        il.Emit(OpCodes.Ldstr, s);
        il.Emit(OpCodes.Ldarg_0);
        il.Emit(OpCodes.Ldarg_1);
        il.EmitCall(OpCodes.Call, typeof(MyClass1).GetMethod("StaticallyDefinedMethod"), null);
        il.Emit(OpCodes.Ret);
        return (Func<int,int,string>)method.CreateDelegate(typeof(Func<int, int, string>));
    }
    public static string StaticallyDefinedMethod(string s, int a, int b)
    {
        return s + "; " + a + "/" + b;
    }
}

dynamic, dynamic.

+2

Source: https://habr.com/ru/post/1796606/


All Articles