本文介绍了复选框使用反射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图拨打:

InputExtensions.CheckBoxFor(h, (dynamic)GetBoolParameterByName(model, propInfo));

下面是我的前pression一边尝试。

Here is my attempt at the expression side.

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需要的前pression Func键&LT; T,BOOL&GT; ,但我不断收到

'模板只能与现场访问,访问属性,一维数组的索引,或单参数自定义索引前pressions使用。

谁能解释一下这个错误是我能做些什么来解决这个问题?

Can anyone explain what this error is an what I can do to fix this?

推荐答案

其实我想通了这一点,CheckBoxFor不接受p.prop.GetValueOrDefault(),你必须做点=> p.prop.Value。虽然你必须确保覆盖名称和标识的元素的属性,因为你会得到prop.Value,而不是道具

I actually figured this out, CheckBoxFor does not accept p.prop.GetValueOrDefault() you must do p=>p.prop.Value. although you have to make sure to override the name and ID attributes on the element because you will get prop.Value instead of prop

var param = Expression.Parameter(typeof(T), "p");
        Expression body = param;
        body = Expression.MakeMemberAccess(Expression.PropertyOrField(body, pi.Name), pi.PropertyType.GetMember("Value").First());
        return Expression.Lambda(body, param);

这篇关于复选框使用反射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 15:25