开发者

transform a lambda expression

开发者 https://www.devze.com 2023-01-10 19:55 出处:网络
I have the following code Expression<Func<IPersistentAttributeInfo, bool>> expression = info => info.Owner== null;

I have the following code

Expression<Func<IPersistentAttributeInfo, bool>> expression = info => info.Owner== null;

and want to tranform it to

Expression<Func<PersistentAttributeInfo, bool>> expression = info => info.Owner== null;

PersistentAttributeInfo is only known开发者_StackOverflow中文版 at runtime though

Is it possible?


If PersistentAttributeInfo is only known at runtime, you obviously cannot write the lambda statically and have the compiler do the heavy lifting for you. You'll have to create a new one from scratch:

Type persistentAttributeInfoType = [TypeYouKnowAtRuntime];
ParameterExpression parameter = Expression.Parameter(persistentAttributeInfoType, "info");
LambdaExpression lambda = Expression.Lambda(
    typeof(Func<,>).MakeGenericType(persistentAttributeInfoType, typeof(bool)), 
    Expression.Equal(Expression.Property(parameter, "Owner"), Expression.Constant(null)),
    parameter);

You can invoke lambda.Compile() to return a Delegate that is analogous to the transformed lambda expression in your example (though of course untyped).

0

精彩评论

暂无评论...
验证码 换一张
取 消