[英]How to extract object reference from property access lambda
Here's a follow-up question to Get name of property as a string . 这是一个后续问题,以获取属性名称作为字符串 。
Given a method Foo (error checking omitted for brevity): 给定方法Foo(为简便起见,省略了错误检查):
// Example usage: Foo(() => SomeClass.SomeProperty)
// Example usage: Foo(() => someObject.SomeProperty)
void Foo(Expression<Func<T>> propertyLambda)
{
var me = propertyLambda.Body as MemberExpression;
var pi = me.Member as PropertyInfo;
bool propertyIsStatic = pi.GetGetMethod().IsStatic;
object owner = propertyIsStatic ? me.Member.DeclaringType : ???;
...
// Execute property access
object value = pi.GetValue(owner, null);
}
I've got the static property case working but don't know how to get a reference to someObject in the instance property case. 我有静态属性的情况下工作,但不知道如何在实例属性情况下获得对someObject的引用。
Thanks in advance. 提前致谢。
MemberExpression
has a property called Expression
, which is the object on which the member access occurs. MemberExpression
具有一个称为Expression
的属性,该属性是进行成员访问的对象。
You can get the object by compiling a function which returns it: 您可以通过编译一个返回它的函数来获取对象:
var getSomeObject = Expression.Lambda<Func<object>>(me.Expression).Compile();
var someObject = getSomeObject();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.