Esempio n. 1
0
        public static Action <object, IDataReader, int> CreateSetValueFromReaderDelegate(MemberInfo member)
        {
            Action <object, IDataReader, int> del = null;

            DynamicMethod dm = new DynamicMethod("SetValueFromReader_" + Guid.NewGuid().ToString("N"), null, new Type[] { typeof(object), typeof(IDataReader), typeof(int) }, true);
            ILGenerator   il = dm.GetILGenerator();

            il.Emit(OpCodes.Ldarg_S, 0);                      //将第一个参数 object 对象加载到栈顶
            il.Emit(OpCodes.Castclass, member.DeclaringType); //将 object 对象转换为强类型对象 此时栈顶为强类型的对象

            var readerMethod = DataReaderConstant.GetReaderMethod(member.GetMemberType());

            //ordinal
            il.Emit(OpCodes.Ldarg_S, 1);                   //加载参数DataReader
            il.Emit(OpCodes.Ldarg_S, 2);                   //加载 read ordinal
            il.EmitCall(OpCodes.Call, readerMethod, null); //调用对应的 readerMethod 得到 value  reader.Getxx(ordinal);  此时栈顶为 value

            EmitHelper.SetValueIL(il, member);             // object.XX = value; 此时栈顶为空

            il.Emit(OpCodes.Ret);                          // 即可 return

            del = (Action <object, IDataReader, int>)dm.CreateDelegate(typeof(Action <object, IDataReader, int>));
            return(del);
        }