using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; namespace JNPF.Common.Extension { public static class LambdaExpressionExtensions { public static void PropertySetValue(this T instance, string propertyName, string value) { if (!PropertySet.ValueFactories.TryGetValue(propertyName, out Action setAction)) { setAction = PropertySet.CreateSetPropertyValueAction(propertyName); PropertySet.ValueFactories.Add(propertyName, setAction); } setAction(instance, value); } public static void PropertySetValue(this T instance, string propertyName, object value) { if (!PropertySet.ValueFactories2.TryGetValue(propertyName, out Action setAction)) { setAction = PropertySet.CreateSetPropertyValueAction2(propertyName); PropertySet.ValueFactories2.Add(propertyName, setAction); } setAction(instance, value); } } public class PropertySet { public static Dictionary> ValueFactories = new Dictionary>(StringComparer.OrdinalIgnoreCase); public static Dictionary> ValueFactories2 = new Dictionary>(StringComparer.OrdinalIgnoreCase); public static Action 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>(setPropertyValue, target, propertyValue).Compile(); } public static Action 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>(assignExp, new[] { target,propertyValue }).Compile(); } } }