对象复制ModelCopier

简介: 对象复制ModelCopier
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, string[] excludeProperties)
    {
        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 && excludeProperties.Contains(toProperty.Name) == false && !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);
                    }
                }
            }
        }
    }
}
目录
相关文章
|
3月前
|
存储
栈内存
栈内存归属于单个线程,也就是每创建一个线程都会分配一块栈内存,而栈中存储的东西只有本线程可见,属于线程私有。 栈的生命周期与线程一致,一旦线程结束,栈内存也就被回收。 栈中存放的内容主要包括:8大基本类型 + 对象的引用 + 实例的方法
35 1
|
9月前
为对象分配内存TLAB
为对象分配内存TLAB
|
9月前
|
Java
【JVM】深入理解Java引用类型:强引用、软引用、弱引用和虚引用
【JVM】深入理解Java引用类型:强引用、软引用、弱引用和虚引用
567 0
|
9月前
|
缓存 Java 程序员
Java垃圾回收: 什么是强引用、软引用、弱引用和虚引用?
Java垃圾回收: 什么是强引用、软引用、弱引用和虚引用?
93 2
|
9月前
|
存储 缓存 算法
对象和数组并不是都是在堆上分配内存的
对象和数组并不是都是在堆上分配内存的
60 0
|
Java
强引用、软引用、弱引用、虚引用的区别?
强引用、软引用、弱引用、虚引用的区别?
95 0
|
存储 程序员 编译器
对象引用和对象指针
对象引用和对象指针
|
存储 缓存 算法
一文了解垃圾回收算法中的引用计数算法
本文介绍将简要介绍一种基本的回收算法:引用计数算法[Collins,1960],英文名 reference counting。
一文了解垃圾回收算法中的引用计数算法
|
算法 Java 调度
【可达性分析、强软弱虚引用、gc的过程中对象是否能回收、三色标记、跨代引用】
【可达性分析、强软弱虚引用、gc的过程中对象是否能回收、三色标记、跨代引用】
148 0
JVM对象引用与内存分配策略
JVM对象引用与内存分配策略