Dynamic Expression from the Property of the object

2019-08-13 15:20发布

i'm starting to explore dynamic expressions, so please help me to solve one issue. I have an object

    public class Categorisation{
       string Name{get;set;}
    }

    public class Client{
       public Categorisation Categorisation{get;set;}
}

All I need is to write a dynamic expression and call Categorisation.Name.Equals("A1") from Client object.

x=>x.Categorisation.Name.Equals("A1")

How can I do this using Expressions?

   var param = Expression.Parameter(typeof(Client));
   var prop = Expression.Property(param, typeof(Client).GetProperty("Categorisation"));
   var argument = Expression.Constant("A1");
   var method = typeof(string).GetMethod("Equals", new[] { typeof(string) });
   var call = Expression.Call(prop, method);
   var expr = Expression.Lambda<Func<Client, bool>>(call, param);

Of course this code is wrong and I call method Equals from Categorisation property and not from Name of Categorisation. But how to invoke Name property?

标签: c# lambda
1条回答
The star\"
2楼-- · 2019-08-13 15:56
var param = Expression.Parameter(typeof(Client));
var prop = Expression.Property(param, typeof(Client).GetProperty("Categorisation"));
var namePropExpr = Expression.Property(prop, "Name");
var argument = Expression.Constant("A1");
var method = typeof(string).GetMethod("Equals", new[] { typeof(string) });
var call = Expression.Call(namePropExpr, method, argument);
var expr = Expression.Lambda<Func<Client, bool>>(call, param);
查看更多
登录 后发表回答