假设我有一个方法,它打印出一个对象的某些属性的名称和值:
public void PrintProperties(object o, params string[] propertyNames)
{
foreach (var propertyName in propertyNames)
{
// get the property info,
// then get the property's value,
// print property-name and -value
}
}
// method can be used like this
PrintProperties(user, "FirstName", "LastName", "Email");
现在不需要再传递一个字符串列表到方法中,我想修改该方法,使得可以使用lambda表达式来指定属性(不确定是否是正确的术语)。
例如,我希望能够以某种方式调用我的方法:
PrintProperties(user, u->u.FirstName, u->u.LastName, u->u.Email);
目标是给方法的用户提供智能感知支持,以防止打字错误。(类似于ASP.NET MVC助手方法,如TextBoxFor(u=>u.Name)
)。
我需要如何定义我的方法,然后如何在方法中获取PropertyInfo
?