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

余計な情報を追加することはできません。「編集を送信中にエラーが発生しました。」 –

関連する問題