Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access object property value by UnaryExpression

Tags:

c#

How can I obtain the object property value by matching the UnaryExpression "Member name" without using "direct" reflection?

public object DoSomething<T>(UnaryExpression uExp, T obj)
   {            
        object res = null;                       
        // NOTE: UnaryExpression contains a property from T type.
        // TODO: get UnaryExpressionMatchingProperty value

        // res = obj.UnaryExpressionMatchingProperty;
        return res;
    }
like image 726
Dryadwoods Avatar asked Mar 17 '26 01:03

Dryadwoods


1 Answers

This should produce the value or null if the structure of the unary expression is not as expected:

var prop = ((uExp.Operand as MemberExpression)?.Member as PropertyInfo);
if (prop?.CanRead == true) { // Needs "== true" because ?. makes Nullable<bool>
    res = prop.GetValue(obj);
}
like image 187
Sergey Kalinichenko Avatar answered Mar 19 '26 15:03

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!