c# emit代码,运行时,报 “操作可能会破坏运行时稳定性”


一、出现问题的代码简介

由于需要动态的生成SQL参数方法,所以采用emit动态创建每个实体类所对应的sqlcommand,

     Type[] DynamicMethodArgs = new Type[] { typeof(DbParamObject), typeof(DbOperType) };
              DynamicMethod dynMethod = new DynamicMethod(string.Format("bossMainMssqlCreateDbCommand_{0}", modelName),
	      typeof(SqlCommand), DynamicMethodArgs, true);
              ILGenerator il = dynMethod.GetILGenerator();
 
              il.Emit(OpCodes.Nop);

              LocalBuilder testCommand = il.DeclareLocal(typeof(SqlCommand));
              il.Emit(OpCodes.Newobj, typeof(SqlCommand).GetConstructor(Type.EmptyTypes)); //实例化一个SQlCommand 类似 sqlCommand t = new SqlCommand();
              il.Emit(OpCodes.Stloc, testCommand);
              il.Emit(OpCodes.Ldloc, testCommand);
              il.Emit(OpCodes.Ldstr, commandText); //将命令压入到计算机栈中
              il.Emit(OpCodes.Callvirt, typeof(SqlCommand).GetMethod("set_CommandText", new Type[] { typeof(string) })); //调用方法,并将栈中命令放入commandText参数中

       il.Emit(OpCodes.Ldloc, testCommand);
               il.Emit(OpCodes.Ret);


二、代码修正

 修改动态方法的构造方法来跳过JIT的安全检查:
Type typeOwner = typeof(DbParamObject);
 DynamicMethod dynMethod = new DynamicMethod(string.Format("bossMainMssqlCreateDbCommand_{0}", modelName), typeof(SqlCommand), DynamicMethodArgs, typeOwner);