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

    }
    }

  • 相关阅读:
    22:django 配置详解
    21:序列化django对象
    20:django中的安全问题
    19:django 分页
    HTML 标签(一)
    流程图学习绘制
    HTTP原理
    终端的颜色代码
    Python 进程 线程总结
    Python Select模型
  • 原文地址:https://www.cnblogs.com/zcm123/p/6689623.html
Copyright © 2011-2022 走看看