基于属性名返回属性值

时间:2015-01-16 13:58:12

标签: c# linq lambda expression-trees

如何在C#中构建表达式树,根据属性的名称返回属性的值

Func<Foo, long> getValue(string propertyName)
{
    // i think that the beginning of the expression tree would look like this
    // but i'm not sure this is correct
    var inputParameter = Expression.Parameter(typeof(Foo));
    var desiredProperty = typeof(Foo).GetProperty(propertyName);
    var valueOfProperty = Expression.Property(inputParameter, desiredProperty);
    // ... ???   todo: expression that returns value
}

调用此函数看起来像这是传递给Linq的Select方法的另一个表达式的一部分:

value = getValue("Bar").Invoke(FooInstance)

1 个答案:

答案 0 :(得分:1)

应该足够了:

var lambda = Expression.Lambda<Func<Foo, long>>(valueOfProperty, inputParameter);
return lambda.Compile();

无论如何 - 当你可以通过反射直接获得价值时,建立表达式的目的是什么?

return someFoo => (long)desiredProperty.GetValue(someFoo);