alielie
2026-04-16 1afe548ac40cc7f975917ef9bf2e156595cf81f3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
 
namespace HMI.Core.Util
{
    public class BeanUtil
    {
        public static void Copy<S, T>(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<T> ReadBeanFromDataTable<T>(DataTable table)
        {
            if (table == null || table.Rows.Count <= 0) return new List<T>();
 
            List<T> list = new List<T>();
            foreach (DataRow row in table.Rows)
            {
                T bean = Activator.CreateInstance<T>();
                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;
        }
    }
}