public static CreateObject CreateConstructorMethod(Type objType, TypeInfo objTypeInfo = null) { CreateObject c; if (objTypeInfo == null) objTypeInfo = objType.GetTypeInfo(); var n = objTypeInfo.Name + ".ctor"; if(objTypeInfo.IsClass) { var dynMethod = new DynamicMethod(n, objType, Type.EmptyTypes); var ilGen = dynMethod.GetILGenerator(); var ct = objTypeInfo.GetConstructor(Type.EmptyTypes) ?? objTypeInfo.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, Type.EmptyTypes, null); if (ct == null) return null; ilGen.Emit(OpCodes.Newobj, ct); ilGen.Emit(OpCodes.Ret); c = (CreateObject)dynMethod.CreateDelegate(typeof(CreateObject)); } else { var dynMethod = new DynamicMethod(n, typeof(object), null, objType); var ilGen = dynMethod.GetILGenerator(); var lv = ilGen.DeclareLocal(objType); ilGen.Emit(OpCodes.Ldloca_S, lv); ilGen.Emit(OpCodes.Initobj, objType); ilGen.Emit(OpCodes.Ldloc_0); ilGen.Emit(OpCodes.Box, objType); ilGen.Emit(OpCodes.Ret); c = (CreateObject)dynMethod.CreateDelegate(typeof(CreateObject)); } return c; }