手动创建表达式树

时间:2014-09-30 23:10:55

标签: c# .net lambda expression-trees

我有课程

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; }
}

我如何构建这个lambda

Expression<Func<MyModel, string>> exp = m => m.Map.MyProperty1;

手动使用表达式树?

2 个答案:

答案 0 :(得分:3)

像这样:

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

答案 1 :(得分:0)

您可以使用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.