Creating expression tree for accessing a Generic type's property

岁酱吖の 提交于 2020-06-10 02:53:29

问题


I need to write a generic method which takes the instance of the generic type and the property name in string format and return an Expression tree

I need to convert a simple lambda expression

a => a.SomePropertyName

where a is generic type which will have a property by the name SomePropertyName

I know that we can get the property information using the following reflection code

System.Reflection.PropertyInfo propInfo = a.GetType().GetProperty("SomePropertyName");

This might be very simple, but I'm not well versed with Expression trees, If there is a similar question, please link it and close this


回答1:


Assuming the parameter type and return type aren't known in advance, you may have to use some object, but fundamentally this is just:

var p = Expression.Parameter(typeof(object));
var expr = Expression.Lambda<Func<object, object>>(
    Expression.Convert(
        Expression.PropertyOrField(
             Expression.Convert(p, a.GetType()), propName), typeof(object)), p);

If the input and output types are known, you can tweak the Func<,> parameters, and maybe remove the Expression.Convert. At the extreme end you can get a lambda without knowing the signature of lambda, via:

var p = Expression.Parameter(a.GetType());
var expr = Expression.Lambda(Expression.PropertyOrField(p, propName), p);



回答2:


You can use this:

var p = Expression.Parameter(a.GetType(), "x");
var body = Expression.Property(p, "SomePropertyName");

Expression.Lambda(body, p);


来源:https://stackoverflow.com/questions/14500604/creating-expression-tree-for-accessing-a-generic-types-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!