复制model数据
using System;
using System.Collections.Generic;
using System.ComponentModel;
namespace RedFoxCms.Component.Utils.Extensions
{
/// <summary>
/// 对象复制
/// </summary>
public static class ModelCopier
{
public static void CopyCollection<T>(this IEnumerable<T> from, ICollection<T> to)
{
if (from == null || to == null || to.IsReadOnly)
{
return;
}
to.Clear();
foreach (T element in from)
{
to.Add(element);
}
}
public static void CopyModel(this object from, object to)
{
if (from == null || to == null)
{
return;
}
var fromProperties = TypeDescriptor.GetProperties(from);
var toProperties = TypeDescriptor.GetProperties(to);
foreach (PropertyDescriptor fromProperty in fromProperties)
{
var toProperty = toProperties.Find(fromProperty.Name, true /* ignoreCase */);
if (toProperty == null || toProperty.IsReadOnly) continue;
// Can from.Property reference just be assigned directly to to.Property reference?
var isDirectlyAssignable = toProperty.PropertyType.IsAssignableFrom(fromProperty.PropertyType);
// Is from.Property just the nullable form of to.Property?
var liftedValueType = (!isDirectlyAssignable) && (Nullable.GetUnderlyingType(fromProperty.PropertyType) == toProperty.PropertyType);
if (!isDirectlyAssignable && !liftedValueType) continue;
var fromValue = fromProperty.GetValue(@from);
if (isDirectlyAssignable || (fromValue != null))
{
toProperty.SetValue(to, fromValue);
}
}
}
}
}