简体   繁体   English

创建表达式树以访问Generic类型的属性

[英]Creating expression tree for accessing a Generic type's property

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 我需要转换一个简单的lambda表达式

a => a.SomePropertyName

where a is generic type which will have a property by the name SomePropertyName 其中a是泛型类型, 它将具有名称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 这可能很简单,但我不熟悉表达式树,如果有类似问题,请链接并关闭此

Assuming the parameter type and return type aren't known in advance, you may have to use some object , but fundamentally this is just: 假设事先不知道参数类型和返回类型,您可能必须使用某个object ,但从根本上说这只是:

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 . 如果已知输入和输出类型,则可以调整Func<,>参数,并可能删除Expression.Convert At the extreme end you can get a lambda without knowing the signature of lambda , via: 在极端情况下,您可以在不知道lambda 签名的情况下获得lambda ,通过:

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

You can use this: 你可以用这个:

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

Expression.Lambda(body, p);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM