2016-09-29 50 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

太糟糕了,我無法添加額外的信息,因爲它會出現'發生錯誤提交編輯.' –