如何从MemberExpression获取属性值

时间:2017-04-04 21:30:15

标签: c# reflection

我试图通过MemberExpression获取属性值。

例如,给定以下对象,我想在“Id”属性中获取Guid值。

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

我有一个被调用的事件,它有一个传递给该事件的MemberExpression。 MemberExpression参数表示Employee.Id属性。如何从MemberExpression中获取“Id”的 VALUE ?我试图使用的代码如下:

(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
}

1 个答案:

答案 0 :(得分:0)

此时你有2个属性可以让你双向间接。

它错过了一个入口点:对#34; BusinessObjects"

的引用

然后致电

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