41 lines
1.5 KiB
C#
41 lines
1.5 KiB
C#
using System;
|
|
using System.Collections.Concurrent;
|
|
using System.Collections.Generic;
|
|
using System.Reflection;
|
|
|
|
namespace Xylem.Common.Utils.Clone
|
|
{
|
|
public static class ReflectionExtensions
|
|
{
|
|
private static readonly ConcurrentDictionary<Type, IDictionary<Func<Object, Object[], Object>, Action<Object, Object, Object[]>>> metadata
|
|
= new ConcurrentDictionary<Type, IDictionary<Func<Object, Object[], Object>, Action<Object, Object, Object[]>>>();
|
|
|
|
public static void CloneProperties<T>(T source, T destination) //where T : class
|
|
{
|
|
var type = typeof(T);
|
|
var properties = metadata.GetOrAdd(type, AddTypeProperties);
|
|
|
|
foreach (var kvp in properties)
|
|
{
|
|
var getter = kvp.Key;
|
|
var setter = kvp.Value;
|
|
var value = getter(source, null);
|
|
setter(destination, value, null);
|
|
}
|
|
}
|
|
|
|
private static IDictionary<Func<Object, Object[], Object>, Action<Object, Object, Object[]>> AddTypeProperties(Type type)
|
|
{
|
|
var properties = new Dictionary<Func<Object, Object[], Object>, Action<Object, Object, Object[]>>();
|
|
|
|
foreach (var property in type.GetProperties(BindingFlags.Instance | BindingFlags.Public))
|
|
{
|
|
if (property.CanWrite)
|
|
{
|
|
properties[property.GetValue] = property.SetValue;
|
|
}
|
|
}
|
|
return properties;
|
|
}
|
|
}
|
|
} |