2016-09-29 51 views
0

如何动态创建表达式。从PropertyInfo动态创建表达

我有一个自定义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对象创建表达式?

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

太糟糕了,我无法添加额外的信息,因为它会出现'发生错误提交编辑.' –