从PropertyInfo动态创建表达式

本文关键字:表达式 创建 动态 PropertyInfo | 更新日期: 2023-09-27 18:09:40

如何动态创建表达式

我有一个自定义编辑器:

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对象创建表达式?

从PropertyInfo动态创建表达式

我想你应该是这样的:

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