zoukankan      html  css  js  c++  java
  • .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(待续)

         

  • 相关阅读:
    Win7+Centos7双系统安装/树莓派安装Centos7
    C++学习笔记
    Ubuntu Codeblocks配置Eigen Sophus
    Java笔记
    解决Mac下AndroidStudio内容时卡顿
    解决Android RadioGroup跑到输入法上面
    Activity去掉标题不成功的解决方法
    Synergy屏幕共享键鼠 (for Mac&Ubuntu)
    Android 限制控件多次点击
    Bitmap 创建、转换、圆角、设置透明度
  • 原文地址:https://www.cnblogs.com/kangao/p/6640628.html
Copyright © 2011-2022 走看看