How to create Expression<Func<TModel, TProperty>>;

喜你入骨 提交于 2019-12-30 06:54:09

问题


Is it possible to create Expression<Func<TModel, bool>>() which can be used in different htmlHelpers (for instance in CheckBoxFor()), if I have a model object

this HtmlHelper<TModel> htmlHelper

and name of the property (through reflection).


回答1:


Sure:

static Expression<Func<TModel,TProperty>> CreateExpression<TModel,TProperty>(
    string propertyName)
{
    var param = Expression.Parameter(typeof(TModel), "x");
    return Expression.Lambda<Func<TModel, TProperty>>(
        Expression.PropertyOrField(param, propertyName), param);
}

then:

var lambda = CreateExpression<SomeModel, bool>("IsAlive");


来源:https://stackoverflow.com/questions/16217410/how-to-create-expressionfunctmodel-tproperty

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