如何创建表达式来; Func键<的TModel,TProperty>取代;
问题描述:
是否有可能创建表达式来; Func键<的TModel,布尔>>()
可在不同htmlHelpers(例如在使用CheckBoxFor()
),如果我有一个模型对象
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).
答
当然:
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");