You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
34 lines
1.2 KiB
34 lines
1.2 KiB
1 year ago
|
using System.Linq.Expressions;
|
||
1 year ago
|
using System.Reflection;
|
||
|
|
||
1 year ago
|
namespace StabilityMatrix.Core.Helper;
|
||
1 year ago
|
|
||
|
public static class Expressions
|
||
|
{
|
||
|
public static (string propertyName, Expression<Action<T, TValue>> assigner)
|
||
|
GetAssigner<T, TValue>(Expression<Func<T, TValue>> propertyAccessor)
|
||
|
{
|
||
|
if (propertyAccessor.Body is not MemberExpression memberExpression)
|
||
|
{
|
||
|
throw new ArgumentException(
|
||
|
$"Expression must be a member expression, not {propertyAccessor.Body.NodeType}");
|
||
|
}
|
||
|
|
||
|
var propertyInfo = memberExpression.Member as PropertyInfo;
|
||
|
if (propertyInfo == null)
|
||
|
{
|
||
|
throw new ArgumentException(
|
||
|
$"Expression member must be a property, not {memberExpression.Member.MemberType}");
|
||
|
}
|
||
|
|
||
|
var propertyName = propertyInfo.Name;
|
||
|
var typeParam = Expression.Parameter(typeof(T));
|
||
|
var valueParam = Expression.Parameter(typeof(TValue));
|
||
|
var expr = Expression.Lambda<Action<T, TValue>>(
|
||
|
Expression.Assign(
|
||
|
Expression.MakeMemberAccess(typeParam, propertyInfo),
|
||
|
valueParam), typeParam, valueParam);
|
||
|
return (propertyName, expr);
|
||
|
}
|
||
|
}
|