laatzen/Common/CommonConsole/ReflectionExtensions.cs
2024-01-24 17:14:10 +01:00

44 lines
1.5 KiB
C#

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Reflection;
namespace CommonConsole
{
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 CopyTo<T>(this 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;
}
}
}