Reputation: 36672
I want to create a method on RunTime. I want the user to enter a string and the method's name will be DynamicallyDefonedMethod_#### (ends with the user string).
i want the same string to be embeded in the method's body: It will call StaticallyDefinedMethod (####, a, b)
Something like:
public MyClass1 DynamicallyDefonedMethod_#### (int a, int b)
{
return StaticallyDefinedMethod (####, a, b)
}
The idea is that the user will create a new method on runtime and invoke it afterward (with a, b parameters).
i googled C# reflection but found no easy way of doing that. Does someone knows how to do it simply ?
Regards,
Upvotes: 3
Views: 478
Reputation: 1064184
As already noted (comments), the easier approach is just to use a lambda:
Func<int,int,Whatever> func = (a,b) => StaticallyDefinedMethod(s,a,b);
but you can also use meta-programming for this (below). Here you control the method name, and have more flexibility (not that you need it here). But note that this doesn't really add a method to the type - the dynamic method is separate and disconnected. You can't really add members to types at runtime.
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;
}
}
A final thought here might be to use dynamic
, but it is very hard to choose names at runtime with dynamic
.
Upvotes: 2