动态创建Expression.Lambda的通用类型

时间:2019-03-06 09:18:58

标签: c# lambda

我想创建lambda表达式,输入:

Expression.Lambda <Func<T,TProperty>>

但不知道TProperty,将其保存在集合中。

public BuilderMapping<T> AutoMap()
{
    var type = typeof(T);
    var props = type.GetProperties(BindingFlags.Public);
    foreach (var propertyInfo in props)
    {
        var param = Expression.Parameter(typeof(T));
        var body = Expression.PropertyOrField(param, propertyInfo.Name);

        // propertyInfo.PropertyType == TProperty
        //  I have not TProperty
        var exp = Expression.Lambda<Func<T, TProperty>>(body, param);

        var prop = new PropertyDescriptor<T, TProperty>
        {
            Selector = exp
        };
        _descriptorColumn.Add(prop);
    }
    return this;
}

1 个答案:

答案 0 :(得分:0)

var delegateType = typeof(Func<,>).MakeGenericType(typeof(T), propertyInfo.PropertyType);
var exp = Expression.Lambda(delegateType, body, param);

PropertyDescriptor<T, TProperty>将需要类似的处理,我认为最简单的方法是:

dynamic prop = Activator.CreateInstance(typeof(PropertyDescriptor<,>).MakeGenericType(typeof(T), propertyInfo.PropertyType));
prop.Selector = (dynamic)exp;