c# 反射得到实体类的字段名称和值,DataTable转List<T>
2016-12-29 00:00
316 查看
/// <summary> /// 反射得到实体类的字段名称和值 /// var dict = GetProperties(model); /// </summary> /// <typeparam name="T">实体类</typeparam> /// <param name="t">实例化</param> /// <returns></returns> public static Dictionary<object, object> GetProperties<T>(T t) { var ret = new Dictionary<object, object>(); if (t == null) { return null; } PropertyInfo[] properties = t.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public); if (properties.Length <= 0) { return null; } foreach (PropertyInfo item in properties) { string name = item.Name; object value = item.GetValue(t, null); if (item.PropertyType.IsValueType || item.PropertyType.Name.StartsWith("String")) { ret.Add(name, value); } } return ret; } //通过反射获取实体类 字段名和字段值 RBAC.Model.SY_ADMIN model = new RBAC.Model.SY_ADMIN(); var dict = GetProperties(model); foreach (var item in dict) { str += string.Format("{0}-----{1}<br/>", item.Key, item.Value); }
/* IList<Model1> t1 = DataTableToList<Model1>(dt); */ /// <summary> /// DataTable利用泛型填充实体类 /// </summary> /// <typeparam name="T">实体类</typeparam> /// <param name="table">dt</param> /// <returns></returns> public static IList<T> DataTableToList<T>(DataTable table) { IList<T> list = new List<T>(); T t = default(T); PropertyInfo[] propertypes = null; string tempName = string.Empty; foreach (DataRow row in table.Rows) { t = Activator.CreateInstance<T>(); propertypes = t.GetType().GetProperties(); foreach (PropertyInfo pro in propertypes) { tempName = pro.Name; if (table.Columns.Contains(tempName)) { object value = MSCL.Until.IsNullOrDBNull(row[tempName]) ? null : row[tempName]; pro.SetValue(t, value, null); } } list.Add(t); } return list; }
相关文章推荐
- c# xml操作类 比较齐全
- c# 多线程传递参数以及任务
- C#一款比较美观的验证码
- C#用SerialPort实现串口通讯
- TreeView(C#)无限目录树代码片段
- C#里获取相关日期 例如做报表时某段时间(如本年度、本季度、本月、本周、上周等)
- c# datetime与 timeStamp(unix时间戳) 互相转换
- C# WinForm获取当前路径汇总
- C# 屏幕监控 自动截屏程序 主窗体隐藏,仅在进程中显示
- c#使用GDI+简单绘图(二)
- c# 【MVC】WebApi开发实例
- C#执行DOS命令(CMD命令)
- C# 使用Parallel并行开发Parallel.For、Parallel.Foreach实例
- C#解析XML详解(XPath以及带命名空间NameSpace)
- C# Async/await 异步多线程编程
- c#设置软件开机自动运行,修改注册表
- C#(WinForm)实现软件注册
- C#windows service服务安装、注册、判断服务是否存在、是否启动
- c#字符串中包含的运算符按正常计算 例如按四则运算等,类似公式计算,很好很强大
- C# 局域网聊天 发送信息