从PropertyInfo动态创建表达式

时间:2016-09-29 11:17:55

标签: c# asp.net-mvc

如何动态创建表达式。

我有一个自定义的EditorFor:

public static class MvcExtensions
{
    public static MvcHtmlString GSCMEditorFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, QuestionMetadata metadata)
    {
        return System.Web.Mvc.Html.EditorExtensions.EditorFor(html, metadata.Expression<TModel, TValue>());
    }
}

我想这样称呼它:

    @foreach (var questionMetaData in Model.MetaData)
    {
        @Html.GSCMEditorFor(questionMetaData);
    }

我的QuestionMetaData类看起来像这样:

public class QuestionMetadata
{
    public PropertyInfo Property { get; set; }

    public Expression<Func<TModel, TValue>> Expression<TModel, TValue>()
    {
        return ///what;
    }
}

我正在宣传:

    public IList<QuestionMetadata> GetMetaDataForApplicationSection(Type type, VmApplicationSection applicationSection)
    {
        var props = type.GetProperties().Where(prop => Attribute.IsDefined(prop, typeof(ApplicationQuestionAttribute)) &&
                                            applicationSection.Questions.Select(x => x.Name).ToArray().Contains(prop.Name));

        var ret = props.Select(x => new QuestionMetadata { Property = x }).ToList();

        return ret;
    }

如何从PropertyInfo对象创建表达式?

1 个答案:

答案 0 :(得分:0)

我想你想要这样的东西:

public class QuestionMetadata
{
    public PropertyInfo PropInfo { get; set; }

    public Expression<Func<TModel, TValue>> CreateExpression<TModel, TValue>()
    {
        var param = Expression.Parameter(typeof(TModel));
        return Expression.Lambda<Func<TModel, TValue>>(
            Expression.Property(param, PropInfo), param);
    }
}


public class TestClass
{
    public int MyProperty { get; set; }
}

试验:

QuestionMetadata qm = new QuestionMetadata();
qm.PropInfo = typeof(TestClass).GetProperty("MyProperty");
var myFunc = qm.CreateExpression<TestClass, int>().Compile();


TestClass t = new TestClass();
t.MyProperty = 10;

MessageBox.Show(myFunc(t).ToString());