Runtime method generation with DynamicMethod

55 views Asked by At

I have an HelloWorld method with some logic in it. I have to generate many methods with different names that have same logic implemantation as HelloWorld. If HelloWorld method don't have any parameters it's easy to do. Problem starts when I have to pass some parameters to HelloWorld using DynamicMethod. Here is a pice of code to help you understand.

public string HelloWorld(string Greeting)
{
    return Greeting;
}

public void MethodGenerator()
{
   MethodInfo HelloWorldMethod = typeof(MyClass).GetMethod("HelloWorld");
   DynamicMethod DM = new DynamicMethod("HelloWorld", typeof(string), new Type[] { typeof(MyClass) });
   ILGenerator IL = DM.GetILGenerator();
   IL.Emit(OpCodes.Ldarg_0);
   IL.Emit(OpCodes.Call, HelloWorldMethod);
   IL.Emit(OpCodes.Ret);
   Func<MyClass, string> DMDelegate = (Func<MyClass, string>)DM.CreateDelegate(typeof(Func<MyClass, string>));
   string Result = DMDelegate(MyObject);
} 

Please help me to modify this code for my case. Thanks in advance.

P.S. I've already googled it, and didn't found anything for my case. Here are some google results that I used

Used Code example

Another example

0

There are 0 answers