本文主要是介绍C# 将DataTable反射成实体类(高效),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
工具类实现(直接复制粘贴)
public class DataTableModelConvertHelper{public static List<T> ConvertList<T>(DataTable table) where T : class{List<ResultArgs<string, string, Type, System.Reflection.PropertyInfo>> lstArgses = new List<ResultArgs<string, string, Type, System.Reflection.PropertyInfo>>();var props = typeof(T).GetProperties();foreach (var cln in props)//获取实体类的属性及属性类型{lstArgses.Add(new ResultArgs<string, string, Type, System.Reflection.PropertyInfo>(){Value1 = string.Empty,//Table.ColName 数据表列名Value2 = cln.Name,//Entity.Name 实体类属性名Value3 = cln.PropertyType,//Entity.Type 实体类属性类型Value4 = cln});}foreach (DataColumn cln in table.Columns)//获取数据表DataTable的列名{foreach (var resultArgse in lstArgses){if (resultArgse.Value2.ToLower() == cln.ColumnName.ToLower())//都转换为小写做匹配{resultArgse.Value1 = cln.ColumnName;}}}List<T> lst = new List<T>();foreach (DataRow row in table.Rows){var info = Activator.CreateInstance<T>();foreach (var ocn in lstArgses){if (!string.IsNullOrEmpty(ocn.Value1)){try{//Console.WriteLine("ocn.Value1:{0};ocn.Value2:{1}", ocn.Value1, ocn.Value2);if (ocn.Value4 != null && row[ocn.Value1] != DBNull.Value){var objValue = DataTableModelConvertHelper.ChangeType(row[ocn.Value1], ocn.Value3);//Console.WriteLine("objValue:{0}", objValue);ocn.Value4.SetValue(info, objValue, null);}}catch (Exception ex){Console.WriteLine(ex.ThrowExceptionDetail());}}}lst.Add(info);}return lst;}#region = ChangeType =private static object ChangeType(object obj, Type conversionType){return ChangeType(obj, conversionType, Thread.CurrentThread.CurrentCulture);}private static object ChangeType(object obj, Type conversionType, IFormatProvider provider){#region NullableType nullableType = Nullable.GetUnderlyingType(conversionType);if (nullableType != null){if (obj == null){return null;}return Convert.ChangeType(obj, nullableType, provider);}#endregionif (typeof(System.Enum).IsAssignableFrom(conversionType)){return Enum.Parse(conversionType, obj.ToString());}return Convert.ChangeType(obj, conversionType, provider);}#endregion}public class ResultArgs<T, G>{public T Value1 { set; get; }public G Value2 { set; get; }}public class ResultArgs<T, G, H>{public T Value1 { set; get; }public G Value2 { set; get; }public H Value3 { set; get; }}public class ResultArgs<T, G, H, J>{public T Value1 { set; get; }public G Value2 { set; get; }public H Value3 { set; get; }public J Value4 { set; get; }}
调用方式
//RequestInfo是实体类
//table是Datatable
//将DataTable表格数据转换为Model实体类代码
var lst = DataTableModelConvertHelper.ConvertList<RequestInfo>(table);
这篇关于C# 将DataTable反射成实体类(高效)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!