首页 新闻 会员 周边

请教如何分析表达式树

0
悬赏园豆:100 [已解决问题] 解决于 2011-04-25 12:00

MSDN官方示例:

 

// Add the following using directive to your code file:
// using System.Linq.Expressions;
// Create an expression tree.
Expression<Func<int, bool>> exprTree = num => num < 5;
// Decompose the expression tree.
ParameterExpression param = (ParameterExpression)exprTree.Parameters[0];
BinaryExpression operation
= (BinaryExpression)exprTree.Body;
ParameterExpression left
= (ParameterExpression)operation.Left;
ConstantExpression right
= (ConstantExpression)operation.Right;
Console.WriteLine(
"Decomposed expression: {0} => {1} {2} {3}",
param.Name, left.Name, operation.NodeType, right.Value);
// This code produces the following output:
// Decomposed expression: num => num LessThan 5

但现在的代码却运行不了,请高手指点:

 

 

public class Test
{
public void ExpressionTest()
{
T t
=new T(){ID=1,Name="abc"};
Expression
<Func<T, bool>> exprTree = o => o.ID == t.ID;
ParameterExpression param
= (ParameterExpression)exprTree
.Parameters[
0];
BinaryExpression operation
= (BinaryExpression)exprTree.Body;
MemberExpression left
= (MemberExpression)operation.Left;
MemberExpression right
=
(MemberExpression)operation.Right;
//这里出错

Console.WriteLine(
"Decomposed expression:{0}=>{1}{2}{3}",
param.Name,left.Member.Name,operation.NodeType,right.Value);

}
}
public class T
{
public int ID { get; set; }
public string Name { get; set; }
}

 

MemberExpression right = (MemberExpression)operation.Right;//这一句想得到表达式右边的1,
但程序总是出错,请高手指点
artwl的主页 artwl | 专家六级 | 园豆:16736
提问于:2011-03-10 12:59
< >
分享
最佳答案
0

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Test.ExpressionTest();
}
}

public class Test
{
public static void ExpressionTest()
{
T t
= new T { ID = 1, Name = "test" };
Expression
<Func<T, bool>> exprTree = o => o.ID == t.ID;
// Decompose the expression tree.
ParameterExpression param = (ParameterExpression)exprTree.Parameters[0];
BinaryExpression operation
= (BinaryExpression)exprTree.Body;
MemberExpression left
= (MemberExpression)operation.Left;

MemberExpression right
= (MemberExpression)operation.Right;

var o1
= Expression.Constant(t);

Console.WriteLine(
"Decomposed expression: {0} => {1} {2} {3}",
param.Name, left.Member.Name, operation.NodeType,
((T)o1.Value).ID);
}
}
public class T
{
public int ID { get; set; }
public string Name { get; set; }
}
}
一定请加分....

收获园豆:100
dotNetDR_ | 老鸟四级 |园豆:2078 | 2011-03-14 18:04
谢谢你,你的代码能达到本问题的要求,但更好的方法是用动态编译,具体可参考我的博客,非常感谢
artwl | 园豆:16736 (专家六级) | 2011-03-15 22:48
其他回答(1)
0

不好玩

贺臣 | 园豆:307 (菜鸟二级) | 2011-03-10 14:58
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册