DataTable转换为Entity(反射&&泛型)

public static IEnumerable<T> Parse<T>(IEnumerable<DataRow> rows) where T : class, new()
{
    if (rows == null || Enumerable.FirstOrDefault<DataRow>(rows) == null)
        return (IEnumerable<T>) new T[0];
    PropertyInfo[] properties = typeof (T).GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty);
    List<T> list = new List<T>();
    foreach (DataRow row in rows)
    {
        T instance = Activator.CreateInstance<T>();
        DbHelper.Parse((object) instance, (IEnumerable<PropertyInfo>) properties, row);
        list.Add(instance);
    }
    return (IEnumerable<T>) list;
}


private static void Parse(object obj, IEnumerable<PropertyInfo> properties, DataRow row)
{
    foreach (PropertyInfo propertyInfo in properties)
    {
        if (DataRowExtension.HasValue(row, propertyInfo.Name))
        {
            try
            {
                propertyInfo.SetValue(obj, DbHelper.ConvertType(CultureInfo.CurrentCulture, row[propertyInfo.Name], propertyInfo.PropertyType), (object[]) null);
            }
        }
        catch{ }
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 这是我的第一篇技术性原创文章,平时分享的文章离代码都有点远,一时间不知道怎么写了,真是“万事开头难”,不管怎么样,...
    野鸟阅读 3,805评论 0 0
  • 泛型反射 在运行时,泛型是无效的,所以可以通过反射在运行时将其他类型变量添加到集合,而不需要考虑泛型
    JerichoPH阅读 2,833评论 0 0
  • 泛型类 在类定义的时候,在后面加上<E>,在下面的成员中(属性,方法)的E在用户对E赋值的时候就会变成相应的数据类...
    岁月是首歌阅读 1,287评论 0 0
  • 我们在工作和学习时,经常需要用到PPT,比如毕业答辩、工作汇报、商务提案、老师课件…… 但是对于大多数没有设计基础...
    林挑挑阅读 7,484评论 2 10
  • 这是一个他,一直觉得内在住这个男性,因为生而为她,那男性的感觉被冲淡了许多,是一种中性的感觉,还是能深深体会坚定、...
    天天_TT阅读 1,339评论 1 2