泛型 DataTable转实体

如果泛型T 创建实例 时提示没有new()约束,无法创建实例请确认类后面添加 where T : new() 代码第一个行末尾

 public class Class2<T> where T : new()
    {
        /// <summary>
        /// DataTable转实体
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public List<T> GetList(DataTable dt)
        {
            List<T> modelList = new List<T>();
            //循环行
            foreach (DataRow dr in dt.Rows)
            {                
                T model = new T();
                //循环列
                for (int i = 0; i < dr.Table.Columns.Count; i++)
                {
                    //model与列名称字段是否可以对应  propertyInfo相当于字段
                    PropertyInfo propertyInfo = model.GetType().GetProperty(dr.Table.Columns[i].ColumnName);              
                    if (propertyInfo != null && dr[i] != DBNull.Value)
                        //赋值
                        propertyInfo.SetValue(model, dr[i], null);
                }
                modelList.Add(model);
            }
            return modelList;
        }

    }

猜你喜欢

转载自blog.csdn.net/qq_36809124/article/details/81584970
今日推荐