Ejemplo n.º 1
0
 /// <summary>
 /// IL动态代码(Emit),T转DataRow
 /// </summary>
 public static DataRow ToDataRow(this object obj)
 {
     var type    = obj.GetType();
     var table   = type.CreateTable();
     var builder = DataTableBuilder.CreateBuilder(type);
     {
         var dr = table.NewRow();
         builder.Build(obj, dr);
         return(dr);
     }
 }
Ejemplo n.º 2
0
        /// <summary>
        /// IL动态代码(Emit),List转DataTable(Excel)
        /// </summary>
        public static DataTable ToExcelTable(this IList list)
        {
            var type    = list.GenericType();
            var table   = type.CreateExcelTable();
            var builder = DataTableBuilder.CreateBuilder(type, true);

            foreach (var item in list)
            {
                var dr = table.NewRow();
                builder.Build(item, dr);
                table.Rows.Add(dr);
            }
            return(table);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// IL动态代码,创建委托
        /// </summary>
        public static DataTableBuilder CreateBuilder(Type type, bool iExcel = false)
        {
            var setValueMethod = typeof(DataRow).GetMethod("set_Item", new Type[] { typeof(string), typeof(object) });

            var         dymMethod = new DynamicMethod(type.Name + nameof(DataTableBuilder), null, new Type[] { typeof(object), typeof(DataRow) }, true);
            ILGenerator generator = dymMethod.GetILGenerator();

            foreach (var property in type.PropertiesValue())
            {
                if (iExcel && !property.IExcel())
                {
                    continue;
                }
                Label endIfLabel = generator.DefineLabel();
                if (property.PropertyType.IsGenericType)
                {
                    generator.GetValue(property, type);//获取引用值
                    generator.Emit(OpCodes.Brfalse, endIfLabel);
                }
                generator.Emit(OpCodes.Ldarg_1);
                generator.Emit(OpCodes.Ldstr, property.Column());

                generator.GetValue(property, type);//获取引用值
                generator.Emit(OpCodes.Callvirt, setValueMethod);
                if (property.PropertyType.IsGenericType)
                {
                    generator.MarkLabel(endIfLabel);
                }
            }
            generator.Emit(OpCodes.Ret);

            var builder = new DataTableBuilder
            {
                handler = dymMethod.CreateDelegate(typeof(Action <object, DataRow>))
            };

            return(builder);
        }