如前所述(评论)中,容易方法就是使用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
。