sexta-feira, 24 de julho de 2015

Reflection - Object Copy Properties

using System;
using System.Reflection;
using System.Xml.Serialization;

namespace Lapuinka.Util
{
    public class ObjectUtil
    {
        public static void CopyProperties(object from, object to, Type type)
        {
            foreach (var propertyInfo in type.GetProperties())
            {
                if (propertyInfo.GetCustomAttributes(typeof(XmlIgnoreAttribute), true).Length > 0) continue;
               
                propertyInfo.SetValue(to, propertyInfo.GetValue(from, null), null);
            }
        }

        public static void CopyProperties(object from, object to, Type type, Func<PropertyInfo, object, object, bool> filter)
        {
            foreach (var propertyInfo in type.GetProperties())
            {
                if (propertyInfo.GetCustomAttributes(typeof(XmlIgnoreAttribute), true).Length > 0) continue;
                if (!filter(propertyInfo, from, to)) continue;

                propertyInfo.SetValue(to, propertyInfo.GetValue(from, null), null);
            }
        }
    }
}


Postar um comentário