阅读对象的属性与前pression树属性、对象、pression

由网友(唐伯虎打秋香)分享简介:我想创建一个lambda前pression的动态读取值的对象的每个属性。I want to create a Lambda Expression for every Property of an Object that reads the value dynamically.我到目前为止有:var propert...

我想创建一个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();
}
阅读全文

相关推荐

最新文章