1
This commit is contained in:
39
common/Tnb.Common/Extension/LambdaExpressionExtensions.cs
Normal file
39
common/Tnb.Common/Extension/LambdaExpressionExtensions.cs
Normal file
@@ -0,0 +1,39 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Linq.Expressions;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Tnb.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 class PropertySet<T>
|
||||
{
|
||||
public static Dictionary<string, Action<object, object>> ValueFactories = new Dictionary<string, Action<object, 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();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user