【问题标题】:How to build expressions for reflected properties如何为反射属性构建表达式
【发布时间】:2012-06-11 19:38:58
【问题描述】:

我已经用这个签名构建了一个 MVC Html 助手:

  public static MvcHtmlString EditFieldFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, object additionalViewData = null)

我正在尝试构建另一个帮助器来反映对象的属性,然后为每个反映的属性调用 EditFieldFor。但正如您所见,该方法需要一个表达式。

如何将 PropertyInfo 转换为表达式?

【问题讨论】:

    标签: c# asp.net-mvc reflection expression-trees


    【解决方案1】:

    This answer 告诉我该怎么做。这是我所做的:

    foreach (var propertyInfo in editFields)
    {
        var expParam = Expression.Parameter(typeof(TModel)); // TModel is a generic parameter on this method
        var expProp = Expression.Property(expParam, propertyInfo);
        var expression = Expression.Lambda(expProp, expParam);
    
        var fieldHtml = (MvcHtmlString)typeof (HtmlHelpers)
            .GetMethod("EditFieldFor")
            .MakeGenericMethod(typeof (TModel), propertyInfo.PropertyType)
            .Invoke(null, new object[] {html, expression, null});
    
        editFormHtml.Append(fieldHtml);
    }
    

    【讨论】:

    • 很高兴知道,这是为了发布答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多