ObjectHelper.cs
1.83 KB
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
// ***********************************************************************
//对象COPY/初始化帮助,通常是防止从视图中传过来的对象属性为空,这其赋初始值
//</summary>
// ***********************************************************************
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace Infrastructure
{
public static class ObjectHelper
{
public static T CopyTo<T>(this object source) where T:class, new()
{
var result = new T();
source.CopyTo(result);
return result;
}
public static void CopyTo<T>(this object source, T target)
where T : class,new()
{
if (source == null)
return;
if (target == null)
{
target = new T();
}
foreach (var property in target.GetType().GetProperties())
{
var propertyValue = source.GetType().GetProperty(property.Name).GetValue(source, null);
if (propertyValue != null)
{
if (propertyValue.GetType().IsClass)
{
}
target.GetType().InvokeMember(property.Name, BindingFlags.SetProperty, null, target, new object[] { propertyValue });
}
}
foreach (var field in target.GetType().GetFields())
{
var fieldValue = source.GetType().GetField(field.Name).GetValue(source);
if (fieldValue != null)
{
target.GetType().InvokeMember(field.Name, BindingFlags.SetField, null, target, new object[] { fieldValue });
}
}
}
}
}