如何在.Net中在运行时创建递归方法? 下面是我第一次动态创建阶乘方法:
static void Main()
{
var rec_funcs = RecurFuncs();
Console.WriteLine("Fact result: {0}", rec_funcs.GetMethod("Fact").Invoke(null, new object[] { 10 }));
Console.ReadKey();
}
public static Type RecurFuncs()
{
TypeBuilder FuncBuilder = null;
ModuleBuilder RecursiveFunctionsModule = null;
{
// Dynamic assembly creation
AppDomain myDomain = Thread.GetDomain();
AssemblyName myAsmName = new AssemblyName() { Name = "RecursiveFunctionsAssembly" };
AssemblyBuilder myAsmBuilder = myDomain.DefineDynamicAssembly(myAsmName, AssemblyBuilderAccess.RunAndSave);
RecursiveFunctionsModule = myAsmBuilder.DefineDynamicModule("RecursiveFunctionsModule", "RecursiveFunctions.dll");
FuncBuilder = RecursiveFunctionsModule.DefineType("RecursiveFunctions", TypeAttributes.Public);
}
{
// Fact
MethodBuilder FactMethod = FuncBuilder.DefineMethod("Fact", MethodAttributes.Public | MethodAttributes.Static, typeof(int), new Type[] { typeof(int) });
var n_param = Expression.Parameter(typeof(int), "n");
var method_body = Expression.IfThenElse(
Expression.Equal(n_param, Expression.Constant(0)),
Expression.Constant(1),
Expression.Multiply(
n_param,
Expression.Call(
RecursiveFunctionsModule.GetType("RecursiveFunctions").GetMethod("Fact"),
Expression.Subtract(
n_param,
Expression.Constant(1)))));
LambdaExpression lambda = Expression.Lambda(method_body, n_param);
lambda.CompileToMethod(FactMethod);
}
Type RecursiveFunctionsType = FuncBuilder.CreateType();
return RecursiveFunctionsType;
}
在运行时,我得到以下异常消息:
在创建类型之前,不支持调用的成员。
据我所知,c#表达式需要使用就绪生成类型(在使用时不会创建RecursiveFunctions类型)