我試圖撥打:複選框使用反射
InputExtensions.CheckBoxFor(h, (dynamic)GetBoolParameterByName(model, propInfo));
這是我在表達方面的嘗試。
public Expression GetBoolParameterByName(T source, PropertyInfo pi)
{
var param = Expression.Parameter(typeof(T), "p");
Expression body = param;
typeof (Nullable<>).GetMethod("GetValueOrDefault", BindingFlags.Instance | BindingFlags.Public, Type.DefaultBinder,
new Type[] {typeof (bool)}, null);
var func = typeof(Nullable<bool>).GetMethod("GetValueOrDefault", BindingFlags.Instance | BindingFlags.Public, Type.DefaultBinder,
new Type[] { typeof(bool) }, null);
body = MethodCallExpression.Call(Expression.PropertyOrField(body, pi.Name), func, Expression.Constant(false));
return Expression.Lambda(body, param);
}
我想這會工作,因爲CheckboxFor需要的Func<T,bool>
的表達,但我不斷收到
'Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.'
誰能解釋一下這個錯誤是我能做些什麼來解決這個問題?
唉我想通了,P => p.prop.GetValueOrDefault()不實際上我需要做p => p.prop.Value我只是不知道該怎麼做,我的嘗試是\t \t \t body = Expression.PropertyOrField(Expression.PropertyOrField(body,pi.Name),「Value 「);但這似乎並不奏效 – dbarnes