c# - Expression Tree and Why?

https://www.tutorialsteacher.com/linq/expression-tree

using System;
using System.Linq.Expressions;

namespace LambdaExpression
{
    public class Student
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            // 1-1. Func
            Func<Student, bool> isTeenager = s => s.Age > 12 && s.Age < 20;

            // 1-2. Func expression
            Expression<Func<Student, bool>> inTeenagerExpr = s => s.Age > 12 && s.Age < 20;

            // 1-3. Call Func expression
            bool flag1 = inTeenagerExpr.Compile()(new Student() { Name = "Peter", Age = 12 });

            // 2-1. Action
            Action<Student> printStu = s => Console.WriteLine(s.Name + "-" + s.Age);

            // 2-2. Action expression
            Expression<Action<Student>> printStuExpr = s => Console.WriteLine(s.Name + "-" + s.Age);

            // 2-3. Call Action expression
            printStuExpr.Compile()(new Student() { Name = "Peter", Age = 12 });

            // 3. Manually create expression tree: Func
            ParameterExpression pe = Expression.Parameter(typeof(Student), "s1");
            MemberExpression me = Expression.Property(pe, "Age");
            ConstantExpression ce1 = Expression.Constant(12, typeof(int));
            ConstantExpression ce2 = Expression.Constant(18, typeof(int));
            BinaryExpression be1 = Expression.GreaterThan(me, ce1);
            BinaryExpression be2 = Expression.LessThan(me, ce2);
            BinaryExpression body = Expression.And(be1, be2);
            var expressionTree = Expression.Lambda<Func<Student, bool>>(body, new[] { pe });

            Console.WriteLine("Expression Tree: {0}", expressionTree);
            Console.WriteLine("Expression Tree Body: {0}", expressionTree.Body);
            Console.WriteLine("Number of Parameters in Expression Tree: {0}", expressionTree.Parameters.Count);
            Console.WriteLine("Parameters in Expression Tree: {0}", expressionTree.Parameters[0]);

            var flag3 = expressionTree.Compile()(new Student() { Name = "Perter", Age = 16 });
            var flag4 = expressionTree.Compile()(new Student() { Name = "Perter", Age = 12 });
            var flag5 = expressionTree.Compile()(new Student() { Name = "Perter", Age = 18 });

            // 4. Manually create expression tree: Action
            var expression2 = Expression.Lambda<Action<Student>>(body, pe);
            var returnType = expression2.ReturnType;
        }
    }
}
发布了130 篇原创文章 · 获赞 20 · 访问量 30万+

猜你喜欢

转载自blog.csdn.net/yuxuac/article/details/103506596