从PropertyInfo创建表达式 [英] Create Expression from PropertyInfo
本文介绍了从PropertyInfo创建表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用期望Expression<Func<T, object>>
的API,并使用它在不同对象之间创建映射:
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"
如何从PropertyInfo
创建必要的表达式?这个想法是:
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);
}
推荐答案
您只需要Expression.Property
,然后将其包装在lambda中即可.棘手的一点是,您也需要将结果转换为object
:
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);
这篇关于从PropertyInfo创建表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文