• .NET 复制A对象值到B对象


    1、最基础的ModelCopy

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    
    public static class ModelCopier
    {
        public static void CopyCollection<T>(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(object from, object to) {
            if (from == null || to == null) {
                return;
            }
    
            PropertyDescriptorCollection fromProperties = TypeDescriptor.GetProperties(from);
            PropertyDescriptorCollection toProperties = TypeDescriptor.GetProperties(to);
    
            foreach (PropertyDescriptor fromProperty in fromProperties) {
                PropertyDescriptor toProperty = toProperties.Find(fromProperty.Name, true /* ignoreCase */);
                if (toProperty != null && !toProperty.IsReadOnly) {
                    // Can from.Property reference just be assigned directly to to.Property reference?
                    bool isDirectlyAssignable = toProperty.PropertyType.IsAssignableFrom(fromProperty.PropertyType);
                    // Is from.Property just the nullable form of to.Property?
                    bool liftedValueType = (isDirectlyAssignable) ? false : (Nullable.GetUnderlyingType(fromProperty.PropertyType) == toProperty.PropertyType);
    
                    if (isDirectlyAssignable || liftedValueType) {
                        object fromValue = fromProperty.GetValue(from);
                        if (isDirectlyAssignable || (fromValue != null && liftedValueType)) {
                            toProperty.SetValue(to, fromValue);
                        }
                    }
                }
            }
        }
    
    }

    2、扩展ModelCopy(待续)

         

  • 相关阅读:
    SQL查询SP代码
    MS SQL Server:查询死锁进程(转载)
    批编译、重新编译和计划缓存
    sql like获取以逗号分割的字段内的数据
    SQL Server 2005—数据库管理10个最重要的特点(转载)
    SQL2005数据库镜像配置脚本
    转:SQL 语句优化
    转:SQL SERVER什么时候写日志
    MDX查询几个经典示例
    尾日志备份和时间点还原
  • 原文地址:https://www.cnblogs.com/kangao/p/6640628.html
Copyright © 2020-2023  润新知