songjun
2024-09-04 cc908053e0b5075fbfd27350b6da4b39bca9e550
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
 
namespace BatchService.Framework.Utility
{
    public class ClassValueCopier
    {
        /// <summary>
        /// 复制属性值
        /// </summary>
        /// <typeparam name="D">目标类</typeparam>
        /// <typeparam name="S">源始类</typeparam>
        /// <param name="s">源始类对象实例</param>
        /// <returns></returns>
        public static D Mapper<D, S>(S s)
        {
            if (s == null)
            {
                return default(D);
            }
            D d = Activator.CreateInstance<D>();
            try
            {
                var Types = s.GetType();//获得类型  
                var Typed = typeof(D);
                foreach (PropertyInfo sp in Types.GetProperties())//获得类型的属性字段  
                {
                    foreach (PropertyInfo dp in Typed.GetProperties())
                    {
                        if (dp.Name == sp.Name && dp.PropertyType == sp.PropertyType)//判断属性名是否相同  
                        {
                            dp.SetValue(d, sp.GetValue(s, null), null);//获得s对象属性的值复制给d对象的属性  
                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return d;
        }
        public static D Mapper<D, S>(D d, S s)
        {
            return Mapper<D, S>(d, s, new string[] { });
        }
 
        public static D Mapper<D, S>(D d, S s, params string[] ignoreProperties)
        {
            if (s == null)
            {
                //return default(D);
            }
            var Types = s.GetType();//获得类型  
            var Typed = typeof(D);
            foreach (PropertyInfo sp in Types.GetProperties())//获得类型的属性字段  
            {
                if (ignoreProperties.ToList().FirstOrDefault(p => p.ToLower() == sp.Name.ToLower()) != null)
                {
                    continue;
                }
                foreach (PropertyInfo dp in Typed.GetProperties())
                {
                    if (dp.Name == sp.Name && dp.PropertyType == sp.PropertyType
                        && dp.CanWrite)//判断属性名是否相同  
                    {
                        dp.SetValue(d, sp.GetValue(s, null), null);//获得s对象属性的值复制给d对象的属性  
                        break;
                    }
                }
            }
            return d;
        }
    }
}