开发者

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):

// 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 prope开发者_StackOverflow社区rty case.

Thanks in advance.


MemberExpression has a property called Expression, which is the object on which the member access occurs.

You can get the object by compiling a function which returns it:

var getSomeObject = Expression.Lambda<Func<object>>(me.Expression).Compile();

var someObject = getSomeObject();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜