Using Reflection.Emit to create a class implementing an interface

前端 未结 5 515
暗喜
暗喜 2020-12-14 04:03

I need to generate a class using Reflection.Emit that implements the following interface.

public interface IObject
{
    T Get(string propertyName);         


        
5条回答
  •  暖寄归人
    2020-12-14 04:22

    You forgot to BOX the return:

    internal delegate object FastConstructorHandler(object[] paramters);
    
        private static FastConstructorHandler CreateDelegate(Type Tipo)
        {
            DynamicMethod dynamicMethod = new DynamicMethod(string.Empty,
                typeof(object), new Type[] { typeof(object[]) }, Tipo.Module, false);
    
            ILGenerator ilg = dynamicMethod.GetILGenerator();
    
            ilg.DeclareLocal(Tipo);
            ilg.Emit(OpCodes.Ldloca_S, (byte)0);
            ilg.Emit(OpCodes.Initobj, Tipo);
            ilg.Emit(OpCodes.Ldloc_0);
            ilg.Emit(OpCodes.Box, Tipo);
            ilg.Emit(OpCodes.Ret);
    
            return (FastConstructorHandler)dynamicMethod.CreateDelegate(typeof(FastConstructorHandler));
        }
    

提交回复
热议问题