问题描述
我需要编写一个通用方法,该方法以字符串格式获取通用类型的实例和属性名称,并返回一个表达式树
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
我需要转换一个简单的lambda表达式
I need to convert a simple lambda expression
a => a.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
推荐答案
假设事先不知道参数类型和返回类型,则可能必须使用一些object
,但从根本上讲,这仅仅是:
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);
如果输入和输出类型已知,则可以调整Func<,>
参数,也可以删除Expression.Convert
.在极端情况下,您可以通过以下方式获得lambda ,而无需知道lambda的签名:
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);
这篇关于创建用于访问泛型类型的属性的表达式树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!