public static class PropertyAccessor
{
public static Expression Create<T>(string propertyName)
{
var property = typeof(T).GetProperty(propertyName);
if (property is null)
{
return null;
}
var result = typeof(PropertyAccessor).GetMethod(nameof(CreateExpression))!
.MakeGenericMethod(typeof(T, property.PropertyType)
.Invoke(null, new object[] { propertyName });
}
private static Expression<Func<TIn, TOut>> CreateExpression<TIn, TOut>(string propertyName)
{
var parameter = Expression.Parameter(typeof(TIn));
var body = Expression.Property(parameter, propertyName);
return Expression.Lambda<Func<TIn, TOut>>(body, parameter);
}
}
I'm tried to cast using Convert and other things, but without knowing TIn and TOut in compile time it's unable to cast
Aucun commentaire:
Enregistrer un commentaire