Create Expression from PropertyInfo

风流意气都作罢 提交于 2020-01-22 18:52:26

问题


I'm using an API that expects an Expression<Func<T, object>>, and uses this to create mappings between different objects:

Map(x => x.Id).To("Id__c"); // The expression is "x => x.Id"

How can I create the necessary expression from a PropertyInfo? The idea being:

var properties = typeof(T).GetProperties();

foreach (var propInfo in properties)
{
    var exp = // How to create expression "x => x.Id" ???

    Map(exp).To(name);
}

回答1:


You just need Expression.Property and then wrap it in a lambda. One tricky bit is that you need to convert the result to object, too:

var parameter = Expression.Parameter(x);
var property = Expression.Property(parameter, propInfo);
var conversion = Expression.Convert(property, typeof(object));
var lambda = Expression.Lambda<Func<T, object>>(conversion, parameter);
Map(lambda).To(name);


来源:https://stackoverflow.com/questions/33051184/create-expression-from-propertyinfo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!