BradleyUffner

il generation

Oct 5th, 2018
304
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.04 KB | None | 0 0
  1.         public void CreateModelFactory()
  2.         {
  3.             var modelType = typeof(TImportModel);
  4.  
  5.             var constructor = typeof(TImportModel).GetConstructor(new[] { typeof(int) });
  6.             if (constructor == null)
  7.             {
  8.                 throw new MissingMethodException($"There is no constructor with the signature '(int)' for type '{modelType}'");
  9.             }
  10.             DynamicMethod dynamic = new DynamicMethod(name: string.Empty,
  11.                                                       returnType: modelType,
  12.                                                       parameterTypes: new[] { typeof(int) },
  13.                                                       owner: modelType);
  14.             ILGenerator il = dynamic.GetILGenerator();
  15.  
  16.             il.DeclareLocal(modelType);
  17.             il.Emit(OpCodes.Ldarg_0);
  18.             il.Emit(OpCodes.Newobj, constructor);
  19.             il.Emit(OpCodes.Ret);
  20.  
  21.             _modelFactory = (Func<int, TImportModel>)dynamic.CreateDelegate(typeof(Func<int, TImportModel>));
  22.         }
Advertisement
Add Comment
Please, Sign In to add comment