封装成类的代码: ###类名为`CovertListHelper` ```csharp using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace DAL { public class CovertListHelper { public List convertToList(DataTable dt) where T : new() { //定义集合 List ts = new List(); //获得此模型的类型 Type type = typeof(T); //定义一个临时的变量 string tempName = ""; //遍历datatable中所有数据行 foreach (DataRow dr in dt.Rows) { T t = new T(); //获得此模型的公共属性 PropertyInfo[] propertys = t.GetType().GetProperties(); //遍历所有属性 foreach (PropertyInfo pi in propertys) { //将此属性赋值给临时变量 tempName = pi.Name; //检查datatable是否包含此列 if (dt.Columns.Contains(tempName)) { //判断此属性是否有setter,这个啥意思呢,就是我们的实体层的{get;set;}如果我们的实体有了set方法,就说明可以赋值! if (!pi.CanWrite) continue; { //取值 object value = dr[tempName]; if (value != DBNull.Value) pi.SetValue(t, value, null); } } } //对象添加到泛型集合中 ts.Add(t); } return ts; } } } ``` 应该如何使用? ```csharp //实例化这个类 DAL.CovertListHelper tolist = new CovertListHelper(); //把DataTable转换为List //要转换成的List类型为:UserEntity //需要转换的DataTable为:table List list = tolist.convertToList(table); ``` Last modification:April 1st, 2020 at 04:19 pm © 允许规范转载 Support 如果觉得我的文章对你有用,请随意赞赏 ×Close Appreciate the author Sweeping payments Pay by AliPay Pay by WeChat
大佬这么强的吗
前来打卡,努力学习,不断成长,充实自我
加油ヾ(´・ ・`。)ノ"