2014-04-04 34 views
0

我試圖撥打:複選框使用反射

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.'

誰能解釋一下這個錯誤是我能做些什麼來解決這個問題?

回答

0

我其實已經想通了,CheckBoxFor不接受p.prop.GetValueOrDefault(),你必須做p => p.prop.Value。雖然你必須確保覆蓋名稱和標識的元素的屬性,因爲你會得到prop.Value,而不是道具

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); 
0

我在GetBoolParameterByName方法中看不到任何問題。唯一可能的問題可能是您將一個bool?(如ID)類型的屬性的PropertyInfo傳遞給它。

+0

唉我想通了,P => p.prop.GetValueOrDefault()不實際上我需要做p => p.prop.Value我只是不知道該怎麼做,我的嘗試是\t \t \t body = Expression.PropertyOrField(Expression.PropertyOrField(body,pi.Name),「Value 「);但這似乎並不奏效 – dbarnes