简体   繁体   中英

How to get a property value from a MemberExpression

I am trying to get the property value via a MemberExpression.

For example, given the following object, I want to get the Guid value in the "Id" property.

public class Employee
{
    public Guid Id {get; set}
}

I have an event being called which has a MemberExpression passed to that event. The MemberExpression parameter represents the Employee.Id property. How can I get the VALUE of "Id" from the MemberExpression? The code I'm trying to use is as follows:

(MemberExpression employeeIdMember is parameter to the event)
if ((employeeIdMember.Member as PropertyInfo) != null)
{
    PropertyInfo employeeIdProperty = employeeIdMember.Member as PropertyInfo;
    // at this point employeeIdProperty represents {System.Guid Id}

    PropertyInfo parentObject = (MemberExpression)employeeIdMember.Expression).Member as PropertyInfo;
    // at this point, parentObject represents {BusinessObjects.Employee Employee}

    // HOW to call employeeIdProperty.GetValue(parentObject) to get the Id Property Value?? I've tried this call here, but it does not work
}

at this point you have 2 properties to make you double indirection.

it miss a entry point : a reference to "BusinessObjects"

then call

var businessObjects = ???
var id = employeeIdProperty.GetValue(parentObject.GetValue(businessObjects));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM