方法'.ctor'没有方法体

时间:2015-05-09 21:25:57

标签: c# reflection.emit

这就是我想要创建的

class MenuItemMap : ClassMap<MenuItem>
{
    public MenuItemMap()
    {
        Id(x => x.MenuItemId);
    }
}

我收到错误:

  

输入thistype = tbuilder.CreateType();

     

方法'.ctor'没有方法体。

代码:

AssemblyName asmName = new AssemblyName("MapAssembly");
AppDomain currentDomain = Thread.GetDomain();
AssemblyBuilder builder = currentDomain.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.RunAndSave);
ModuleBuilder mbuilder = builder.DefineDynamicModule("MapModule");
TypeBuilder tbuilder = mbuilder.DefineType("MenuItemMap", TypeAttributes.Public);

Type baseType = typeof(ClassMap<>).MakeGenericType(typeof(MenuItem));
tbuilder.SetParent(baseType);
Type objType = Type.GetType("System.Object");
ConstructorInfo objCtor = objType.GetConstructor(new Type[0]);

Type[] ctorParams = new Type[] { typeof(int), typeof(int), typeof(int) };

ConstructorBuilder pointCtor = tbuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, ctorParams);

Type[] tparams = { typeof(Expression<Func<MenuItem, object>>) };
MethodBuilder methodId = tbuilder.DefineMethod("Id", MethodAttributes.Public, typeof(IdentityPart), tparams);

ILGenerator generator = methodId.GetILGenerator();

generator.DeclareLocal(typeof(System.Single));  //Declares a local variable to the method
generator.Emit(OpCodes.Ldarg_1);    // Loads 1st argument passed to the method
generator.Emit(OpCodes.Add_Ovf);    // adds the two numbers loaded.
            //generator.Emit(OpCodes.Conv_R4);    // Converts the result to float32
generator.Emit(System.Reflection.Emit.OpCodes.Box, typeof(IdentityPart));
            //generator.Emit(OpCodes.Stloc_0);    // Stores it back to local variable.. You can omit this and next line if you wish

Type thistype = tbuilder.CreateType();

//builder.Save("myassembly.dll");  // You name the assembly to save the dll
MethodInfo info = thistype.GetMethod("Id", BindingFlags.Instance | BindingFlags.Public);
object thisObj = Activator.CreateInstance(thistype);

var item = Expression.Parameter(typeof(MenuItem), "x");
var prop = Expression.Property(item, "MenuItemId");
var lambda = Expression.Lambda<Func<MenuItem, object>>(prop, item);

object result = info.Invoke(thisObj, BindingFlags.Public | BindingFlags.CreateInstance, null, new Expression[] { lambda }, Thread.CurrentThread.CurrentCulture);

0 个答案:

没有答案