using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace BatchService.Framework.Utility
{
public class ClassValueCopier
{
///
/// 复制属性值
///
/// 目标类
/// 源始类
/// 源始类对象实例
///
public static D Mapper(S s)
{
if (s == null)
{
return default(D);
}
D d = Activator.CreateInstance();
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 d, S s)
{
return Mapper(d, s, new string[] { });
}
public static D Mapper(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;
}
}
}