use*_*910 1 c# expression expression-trees
我有以下字符串表达式定义对象遍历"eBnum".其中e定义了我的字符串表达式中的根实体
class BTest
{
public int num{get:set;}
}
class Test
{
public int sample {get; set;}
public BTest B {get; set;}
}
static void TestProperty()
{
Test obj = new Test();
obj.sample = 40;
obj.B = new BTest(){ num=5}
Expression propertyExpr = Expression.Property(Expression.Constant(obj),"num");
Console.WriteLine(Expression.Lambda<Func<int>>(propertyExpr).Compile()());
Run Code Online (Sandbox Code Playgroud)
}
在下面的语句Expression.Property(Expression.Constant(obj),"num"); 我能够获得第一级属性"sample"的值,但不能获得第二级属性的值?
我在这里错过了什么吗?我试图基于"num"属性值构建一个二进制表达式.
在查找嵌套属性时,必须创建嵌套属性表达式.
Expression bExpression = Expression.Property(Expression.Constant(obj), "B");
Expression numExpression = Expression.Property(bExpression, "num");
Console.WriteLine(Expression.Lambda<Func<int>>(numExpression).Compile()());//Prints 5
Run Code Online (Sandbox Code Playgroud)