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,
但程序总是出错,请高手指点
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; }
}
}
不好玩