快速问题:
我想显示某些实体的某些属性:
public void DisplayEntity<TEntity>(TEntity entity, params Expression<Func<TEntity, TProperty>> properties)
{
// access the properties values
Console.Write(propertyValue);
}
所以我可以简单地这样做:
DisplayEntity(Contact contact, c => c.Name);
DisplayEntity(Contact contact, c => c.Name, c => c.Tel);
我不确定如何编写DisplayEntity
函数以便您可以执行此操作。
回答
根据弗洛里安的回答,我稍微浓缩了它,与 lambda 表达式的东西保持一致:
static void WriteEntity<T>(T entity, params Expression<Func<T, object>>[] properties)
{
properties.ToList().ForEach(x =>
{
var f = x.Compile();
MemberExpression me;
switch (x.Body.NodeType)
{
case ExpressionType.Convert:
case ExpressionType.ConvertChecked:
var ue = x.Body as UnaryExpression;
me = ((ue != null) ? ue.Operand : null) as MemberExpression;
break;
default:
me = x.Body as MemberExpression;
break;
}
var memberInfo = me.Member;
Console.WriteLine("{0}: {1}", memberInfo.Name, f(entity));
});
}