.NET Expression Tree

Expression Tree 第一个简单的例子。

 [TestMethod]
        public void GodTest()
        {
            Expression<Func<int, int, int>> expression = (a, b) => a + b;

            var func = expression.Compile();
            var r = func(1, 2);
            Assert.AreEqual(3, r);

            var s = Expression.Variable(typeof(string), "s");
            var assignExpression = Expression.Assign(s, Expression.Constant("Hello World!"));

            var callExpression = Expression.Call(null, typeof(Console).GetMethod("WriteLine", new[] { typeof(object) }), s);

            var writeLineExpression = Expression.Lambda<Action>(
                Expression.Block(
                new[] { s }, assignExpression, callExpression));

            var writeLine = writeLineExpression.Compile();
            writeLine();
        }

一个简单的例子:

  class Program
    {
        static void Main(string[] args)
        {
            Expression e1 = Expression.Constant(1);
            Expression e2 = Expression.Constant(2);
            Expression add = Expression.Add(e1, e2);

            var compiled = Expression.Lambda<Func<int>>(add).Compile();
            Console.WriteLine(compiled());
        }
    }

你可能感兴趣的:(express)