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;
|
}
|
}
|
}
|