Files
tnb.server/common/Tnb.Common/Extension/LambdaExpressionExtensions.cs
2023-11-06 19:35:59 +08:00

58 lines
2.7 KiB
C#

using System.Linq.Expressions;
namespace JNPF.Common.Extension
{
public static class LambdaExpressionExtensions
{
public static void PropertySetValue<T>(this T instance, string propertyName, string value)
{
if (!PropertySet<T>.ValueFactories.TryGetValue(propertyName, out Action<object, object> setAction))
{
setAction = PropertySet<T>.CreateSetPropertyValueAction(propertyName);
PropertySet<T>.ValueFactories.Add(propertyName, setAction);
}
setAction(instance, value);
}
public static void PropertySetValue<T>(this T instance, string propertyName, object value)
{
if (!PropertySet<T>.ValueFactories2.TryGetValue(propertyName, out Action<T, object> setAction))
{
setAction = PropertySet<T>.CreateSetPropertyValueAction2(propertyName);
PropertySet<T>.ValueFactories2.Add(propertyName, setAction);
}
setAction(instance, value);
}
}
public class PropertySet<T>
{
public static Dictionary<string, Action<object, object>> ValueFactories = new Dictionary<string, Action<object, object>>(StringComparer.OrdinalIgnoreCase);
public static Dictionary<string, Action<T, object>> ValueFactories2 = new Dictionary<string, Action<T, object>>(StringComparer.OrdinalIgnoreCase);
public static Action<object, object> CreateSetPropertyValueAction(string propertyName)
{
var property = typeof(T).GetProperty(propertyName);
var target = Expression.Parameter(typeof(object));
var propertyValue = Expression.Parameter(typeof(object));
var castTarget = Expression.Convert(target, typeof(T));
var castPropertyValue = Expression.Convert(propertyValue, property!.PropertyType);
var setPropertyValue = Expression.Call(castTarget, property.GetSetMethod()!, castPropertyValue);
return Expression.Lambda<Action<object, object>>(setPropertyValue, target, propertyValue).Compile();
}
public static Action<T, object> CreateSetPropertyValueAction2(string propertyName)
{
var property = typeof(T).GetProperty(propertyName);
var target = Expression.Parameter(typeof(T));
var propExp = Expression.Property(target, propertyName);
var propertyValue = Expression.Parameter(typeof(object));
var castPropertyValue = Expression.Convert(propertyValue, property!.PropertyType);
var assignExp = Expression.Assign(propExp, castPropertyValue);
return Expression.Lambda<Action<T, object>>(assignExp, new[] { target, propertyValue }).Compile();
}
}
}