如何通过匹配 UnaryExpression“成员名称”而不使用“直接”反射来获取对象属性值?
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;
}
如果一元表达式的结构不符合预期,这应该产生值 or null
:
var prop = ((uExp.Operand as MemberExpression)?.Member as PropertyInfo);
if (prop?.CanRead == true) { // Needs "== true" because ?. makes Nullable<bool>
res = prop.GetValue(obj);
}
我是一名优秀的程序员,十分优秀!