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;
}
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With