c# - 使用表达式树读取对象的属性

标签 c# .net lambda expression-trees

我想为动态读取值的对象的每个属性创建一个 Lambda 表达式。

我目前拥有的:

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();
}

当我调用 functionThatGetsValue 时代码运行良好,只要“TypeOfProperty”是硬编码的。我知道我不能动态传递“TypeOfPoperty”。我可以做些什么来实现我的目标?

最佳答案

假设您对 Func<TType, object> 感到满意委托(delegate)(根据上面的评论),你可以使用 Expression.Convert 实现这一目标:

var properties = typeof(TType).GetProperties().Where(p => p.CanRead);

foreach (var propertyInfo in properties)
{
    MethodInfo getterMethodInfo = propertyInfo.GetGetMethod();
    ParameterExpression entity = Expression.Parameter(typeof(TType));
    MethodCallExpression getterCall = Expression.Call(entity, getterMethodInfo);

    UnaryExpression castToObject = Expression.Convert(getterCall, typeof(object));
    LambdaExpression lambda = Expression.Lambda(castToObject, entity);

    var functionThatGetsValue = (Func<TType, object>)lambda.Compile();
}

关于c# - 使用表达式树读取对象的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16436323/

相关文章:

c# - Entity Framework 6 可选的单向关系

c# - 无法作为 webService 访问简单 Controller

c# - 'is' 与 try cast with null check

c# - 在内存中缓存应用程序数据 : MVC Web API

c# - 表达式列表 <Func<T, TProperty>>

c# - 使用 Jquery 将文本附加到 div

c# - 抛出异常时退出循环是否可以?

.net - 我可以在 .NET 中避免 JIT 吗?

Java 流 LambdaExp ForEach_

C#——我们应该检查 lambda 中的传入参数吗?