using System; using System.Collections.Generic; using System.Data; using System.Reflection; namespace HMI.Core.Util { public class BeanUtil { public static void Copy(S source, T target) { Type sourceType = typeof(S); Type targetType = typeof(T); PropertyInfo[] fieldArray = targetType.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); foreach (PropertyInfo field in fieldArray) { string fileName = field.Name; PropertyInfo sourceField = sourceType.GetProperty(fileName); if (sourceField == null) continue; field.SetValue(target, sourceField.GetValue(source)); } } public static List ReadBeanFromDataTable(DataTable table) { if (table == null || table.Rows.Count <= 0) return new List(); List list = new List(); foreach (DataRow row in table.Rows) { T bean = Activator.CreateInstance(); foreach (var prop in typeof(T).GetProperties()) { if (table.Columns.Contains(prop.Name)) { var value = row[prop.Name]; if (value != DBNull.Value) { prop.SetValue(bean, Convert.ChangeType(value, prop.PropertyType)); } } } list.Add(bean); } return list; } } }