[英]Create an expression tree manually
I have the classes 我有课
public class MyModel
{
public MyModel()
{
this.Map = new MyMap();
}
public MyMap Map { get; set; }
}
public class MyMap
{
public string MyProperty1 { get; set; }
public int MyProperty2 { get; set; }
}
How can I construct this lambda 我怎样才能构建这个lambda
Expression<Func<MyModel, string>> exp = m => m.Map.MyProperty1;
manually using Expression Tree? 手动使用表达式树?
Like this: 像这样:
var parameter = Expression.Parameter(typeof (MyModel));
var mapProperty = Expression.Property(parameter, "Map");
var myProperty1 = Expression.Property(mapProperty, "MyProperty1");
var exp = Expression.Lambda<Func<MyModel, string>>(myProperty1, parameter);
You can do this using the PropertyOrField method of Expression, here is a quick example I cooked up using your objects: 您可以使用Expression的PropertyOrField方法执行此操作,这是我使用您的对象编写的一个快速示例:
var model = new MyModel();
var mapExpr = Expression.PropertyOrField(Expression.Constant(model), "Map");
var propExpr = Expression.PropertyOrField(mapExpr, "MyProperty1");
Expression.Lambda<Func<string>>(propExpr).Compile()(); //Outputs the value of MyProperty1 on the variable called model.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.