General method with general arguments

I have the following code to create a func expression to access a class property

public static Expression<Func<TObj, TProperty>> BuildGet<TObj, TProperty>(PropertyInfo property)
{
    Type type = typeof(TObj);
    ParameterExpression arg = Expression.Parameter(type, "x");
    var prop = Expression.Property(arg, property);

    return Expression.Lambda<Func<TObj, TProperty>>(prop, arg);
}

The problem is that I have to go through TObjand TProperty, even if they are known (properties in PropertyInfoclass - .DeclaringTypeand .PropertyType).

Is there any way around this, so I should not explicitly pass them?

The return type must remain as Expression<Func<TObj, TProperty>>

+3
source share
2 answers

Func<TObj, TProperty>, . . , , PropertyInfo , , , , .. , .

Expression, Expression<Func<TObj, TProperty>> , Expression. , ...

+3

TObj? - , .

- :

public static Expression<Func<TObj, TProperty>> BuildGet<TObj, TProperty>
    (TObj obj, TProperty property) { ... }

TObj TProperty, , , PropertyInfo .

+1

Source: https://habr.com/ru/post/1707865/


All Articles