阅读对象的属性与前pression树 [英] Reading Properties of an Object with Expression Trees
本文介绍了阅读对象的属性与前pression树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想创建一个lambda前pression的动态读取值的对象的每个属性。
I want to create a Lambda Expression for every Property of an Object that reads the value dynamically.
我到目前为止有:
var properties = typeof (TType).GetProperties().Where(p => p.CanRead);
foreach (var propertyInfo in properties)
{
var getterMethodInfo = propertyInfo.GetGetMethod();
var entity = Expression.Parameter(typeof (TType));
var getterCall = Expression.Call(entity, getterMethodInfo);
var lambda = Expression.Lambda(getterCall, entity);
var expression = (Expression<Func<TType, "TypeOfProperty">>) lambda;
var functionThatGetsValue = expression.Compile();
}
在code运作良好时,我叫 functionThatGetsValue
只要TypeOfProperty难codeD。我知道我无法通过TypeOfPoperty动态。我能做些什么才达到我的目标?
The code Works well when i call functionThatGetsValue
as long as "TypeOfProperty" is hardcoded. I know that I can't pass the "TypeOfPoperty" dynamically. What can I do to achive my goal?
推荐答案
假设你是开心的 Func键&LT; Af - Ag型,对象&gt;
委托(根据意见以上),您可以使用 防爆pression.Convert
实现这一目标:
Assuming that you're happy with a Func<TType, object>
delegate (as per the comments above), you can use Expression.Convert
to achieve that:
var properties = typeof(TType).GetProperties().Where(p => p.CanRead);
foreach (var propertyInfo in properties)
{
var getterMethodInfo = propertyInfo.GetGetMethod();
var entity = Expression.Parameter(typeof(TType));
var getterCall = Expression.Call(entity, getterMethodInfo);
var castToObject = Expression.Convert(getterCall, typeof(object));
var lambda = Expression.Lambda(castToObject, entity);
var functionThatGetsValue = (Func<TType, object>)lambda.Compile();
}
这篇关于阅读对象的属性与前pression树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文