正如已经指出的(评论),更简单的方法就是使用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
,但是在运行时选择名称非常困难。