zoukankan      html  css  js  c++  java
  • 复制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);
    }
    }
    }

    }
    }

  • 相关阅读:
    pycharm2018.1下载激活(mac平台)
    python 保存登录状态 cookie
    utf-8和utf-8-sig的区别
    AcWing 803. 区间合并
    AcWing 801. 二进制中1的个数
    AcWing 800. 数组元素的目标和
    AcWing 799. 最长连续不重复子序列
    AcWing 795. 前缀和
    AcWing 791. 高精度加法 解题记录
    九州缥缈录 合集序言
  • 原文地址:https://www.cnblogs.com/zcm123/p/6689623.html
Copyright © 2011-2022 走看看