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.
33 lines
1.2 KiB
33 lines
1.2 KiB
using System.Linq.Expressions; |
|
using System.Reflection; |
|
|
|
namespace StabilityMatrix.Core.Helper; |
|
|
|
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); |
|
} |
|
}
|
|
|