如何从MemberExpression获取属性值
问题描述:
我试图通过MemberExpression获取属性值。如何从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
}
答
在这一点上,你有2个属性,让你双重间接。
它错过任何一个入口点:一提到 “的BusinessObjects”
然后调用
var businessObjects = ???
var id = employeeIdProperty.GetValue(parentObject.GetValue(businessObjects));