直接上代码:
/// <summary>
/// 相同类的不同实体例间属性拷贝
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="tOne"></param>
/// <param name="tSecond"></param>
public static void CopyPropertyDifReflection<T>(T tOne, T tSecond)
{
foreach (var itemOut in tSecond.GetType().GetProperties())
{
if (itemOut.CanWrite)
{
var itemIn = tOne.GetType().GetProperty(itemOut.Name);
if (itemIn != null)
{
//值不一样时才更新
var objIn = itemIn.GetValue(tOne);
var objOut = itemOut.GetValue(tSecond);
if (objIn == objOut || (objIn == null && objOut != null && string.IsNullOrEmpty(objOut.ToString())) ||
(objIn != null && objOut == null && string.IsNullOrEmpty(objIn.ToString()))) continue;
if (objIn != null && objIn.Equals(objOut)) continue;
itemOut.SetValue(tSecond, objIn);
}
}
}
}
/// <summary>
/// 不同对象间拷贝相同属性值
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <param name="target"></param>
public static void CopyPropertiesTo<T1,T2>(this T1 source, T2 target)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
if (target == null)
throw new ArgumentNullException(nameof(target));
PropertyInfo[] sourceProperties = source.GetType().GetProperties();
foreach (PropertyInfo sourceProperty in sourceProperties)
{
PropertyInfo targetProperty = target.GetType().GetProperty(sourceProperty.Name);
if (targetProperty != null && targetProperty.CanWrite)
{
targetProperty.SetValue(target, sourceProperty.GetValue(source, null), null);
}
}
}

861

被折叠的 条评论
为什么被折叠?



