【c#】通过类的实例获取类的字段属性

以DataTable为例:

private static List<T> TableToEntity<T>(DataTable dt) where T : class,new()
{
    Type type = typeof(T);
    List<T> list = new List<T>();

    foreach (DataRow row in dt.Rows)
    {
        PropertyInfo[] pArray = type.GetProperties();
        T entity = new T();
        foreach (PropertyInfo p in pArray)
        {
            if (row[p.Name] is Int64)
            {
                p.SetValue(entity, Convert.ToInt32(row[p.Name]), null);
                continue;
            }
            p.SetValue(entity, row[p.Name], null);
        }
        list.Add(entity);
    }
    return list;
}
  

// 调用:

List<User> userList = TableToEntity<User>(YourDataTable); 

 

学习链接:https://www.jb51.net/article/35687.htm

posted @ 2021-04-12 16:14  不溯流光  阅读(352)  评论(0编辑  收藏  举报