日期:2014-05-17  浏览次数:20584 次

C# Emit问题->DataReader 转Entity....
本帖最后由 wangping_li 于 2011-06-29 14:42:22 编辑
正常读取reader.GetInt32的方法如下:

 
il.Emit(OpCodes.Ldloc_S, item);
                il.Emit(OpCodes.Ldarg_0);
                il.Emit(OpCodes.Ldloc_S, colIndices[i]);
                il.Emit(OpCodes.Callvirt, DataRecord_GetInt32);
                il.Emit(OpCodes.Callvirt, columnInfoes[i].SetMethod);


现在加了一个判断,就是当值为IsDBNull的时候,则取DefaultValue,代码如下:

 var local = il.DeclareLocal(columnInfoes[i].Type);//int i
                Label intNull = il.DefineLabel();//is null lable
                Label intCommon = il.DefineLabel();//not null lable              

                il.Emit(OpCodes.Ldloca, local);
                il.Emit(OpCodes.Ldarg_0);//将索引 0 处的局部变量i加载到计算堆栈上->i
                il.Emit(OpCodes.Ldloc_S, colIndices[i]);//index ->为IsDBNull(index)的参数
                il.Emit(OpCodes.Callvirt, DataRecord_IsDBNull);
                il.Emit(OpCodes.Brtrue_S, intNull);//如果is null则转向intNull标签

                il.Emit(OpCodes.Ldarg_0);//i
                il.Emit(OpCodes.Ldloc_S, colIndices[i]);
                il.Emit(OpCodes.Callvirt, DataRecord_GetInt32);
                il.Emit(OpCodes.Br_S, intCommon);//is not null则转向intCommon标签

                //is null
                il.MarkLabel(intNull);
                il.Emit(OpCodes.Ldc_I4, columnInfoes[i].DefaultValue);//为null时这里赋值

                //not null
                il.MarkLabel(intCommon);
                il.Emit(OpCodes.Ldloc_S, item);
                il.Emit(OpCodes.Ldloc, local);
                il.Emit(OpCodes.Callvirt, columnInfoes[i].S