我想创建一个lambda EX pression嵌套属性在运行时从PROPERT的名称。基本上我想创建由指定的拉姆达EX pression:
I am trying to create a lambda expression for a nested property at run-time from the name of the propert. Basically I am trying to create the lambda expression specified by:
var expression = CreateExpression<Foo, object>(foo => foo.myBar.name);
private static Expression CreateExpression<TEntity, TReturn>(Expression<Func<TEntity, TReturn>> expression)
{
return (expression as Expression);
}
使用这些类:
class Foo
{
public Bar myBar { get; set; }
}
class Bar
{
public string name { get; set; }
}
但是,所有我给出的富
的类型和字符串myBar.name
如果它是一个正常的财产,如只需要值myBar
然后我可以使用以下内容:
If it were a normal property such as just needing the value "myBar"
then I could use the following:
private static LambdaExpression GetPropertyAccessLambda(Type type, string propertyName)
{
ParameterExpression odataItParameter = Expression.Parameter(type, "$it");
MemberExpression propertyAccess = Expression.Property(odataItParameter, propertyName);
return Expression.Lambda(propertyAccess, odataItParameter);
}
然而,这code没有嵌套性工作,我不知道如何创建LambdaEx pression做 foo.myBar.name 。
我认为这将是这样的:
GetExpression(Expression.Call(GetExpression(Foo, "myBar"), "name"))
不过,我似乎无法找出如何获得这一切的工作,或是否有更好的方法在运行时做到这一点。
But I can't seem to work out how to get it all working, or if there's a better way to do this at run-time.
你的意思是:
static LambdaExpression CreateExpression(Type type, string propertyName) {
var param = Expression.Parameter(type, "x");
Expression body = param;
foreach (var member in propertyName.Split('.')) {
body = Expression.PropertyOrField(body, member);
}
return Expression.Lambda(body, param);
}
例如:
class Foo {
public Bar myBar { get; set; }
}
class Bar {
public string name { get; set; }
}
static void Main() {
var expression = CreateExpression(typeof(Foo), "myBar.name");
// x => x.myBar.name
}
下一篇:是.NET终结总是执行?NET