C#知識點-表達式目錄樹


原文鏈接:https://www.cnblogs.com/loverwangshan/p/10254730.html

閱讀目錄

1:什么是表達式樹

2:表達式目錄樹與委托

3:使用Expression來進行不同對象的相同名字的屬性映射

4:ORM與表達式樹目錄的關系

 

一:什么是表達式樹

Expression我們稱為是表達式樹,是一種數據結構體,用於存儲需要計算,運算的一種結構,這種結構可以只是存儲,而不進行運算。通常表達式目錄樹是配合Lambda一起來使用的,lambda可以是匿名方法,當然也可以使用Expression來動態的創建!下面我們舉例來說明什么是表達式目錄樹。

先創建一個People的實體,下面會用到

/// <summary>
/// 實體類
/// </summary>
public class People
{
    public int Age { get; set; }
    public string Name { get; set; }
    public int Id;
}
View Code

我們可以通過下面創建表達式目錄樹,我們稱之為A種方式:

Expression<Func<People, bool>> lambda = x => x.Id.ToString().IndexOf("5") >= 0;
View Code

我們還可以使用Expression來動態創建,我們稱之為B種方式:

var peopleParam = Expression.Parameter(typeof(People), "x");//創建一個x,類型為people
//得到x.Id
MemberExpression idParam = Expression.Field(peopleParam, "Id");

//得到ToString方法
MethodInfo toStringWay = typeof(int).GetMethod("ToString", new Type[] { });

//得到IndexOf的方法,然后new Type[]這個代表是得到參數為string的一個方法
MethodInfo indexOfWay = typeof(string).GetMethod("IndexOf", new Type[] { typeof(string) });

//通過下面方法得到x.Id.ToString()
MethodCallExpression tostringResult = Expression.Call(idParam, toStringWay, new Expression[] { });

//通過下面方法得到x.Id.ToString().IndexOf("5") ,MethodCallExpression繼承於Expression
MethodCallExpression indexOfResult = Expression.Call(tostringResult, indexOfWay, new Expression[] { Expression.Constant("5") });

//x.Id.ToString().IndexOf("5")>=0
var lambdaBody = Expression.GreaterThanOrEqual(indexOfResult, Expression.Constant(0));

//得到x => x.Id.ToString().IndexOf("5") >= 0,后面的一個參數指的是x,如果有多個則指定多個
Expression<Func<People,bool>> lambdaResult = Expression.Lambda<Func<People, bool>>(lambdaBody, new ParameterExpression[]
                                                                                                { peopleParam });

//通過lambdaResult.Compile()得到Func<People,bool>這樣的委托,然后Invoke是調用委托
bool result = lambdaResult.Compile().Invoke(new People() { Id = 155 });
View Code

A種和B種得到的結果是一致的,只不過第一種是通過lambda匿名方法來構建,第二種是通過動態的Expression來構建。另外下面的原理也是一樣的

//普通的Lambda表達式
 Func<int,int,int> func = (x,y)=>  x + y - 2;
//表達式目錄樹的Lambda表達式聲明方式
Expression<Func<int, int, int>> expression = (x, y) => x + y - 2;   

//表達式目錄樹的拼接方式實現
ParameterExpression parameterx =  Expression.Parameter(typeof(int), "x");
ParameterExpression parametery =  Expression.Parameter(typeof(int), "y");
ConstantExpression constantExpression = Expression.Constant(2, typeof(int));
BinaryExpression binaryAdd = Expression.Add(parameterx, parametery);
BinaryExpression binarySubtract = Expression.Subtract(binaryAdd, constantExpression);
Expression<Func<int, int, int>> expressionMosaic = Expression.Lambda<Func<int, int, int>>(binarySubtract, new ParameterExpression[]
{
       parameterx,
       parametery
});

int ResultLambda = func(5, 2);
int ResultExpression = expression.Compile()(5, 2);
int ResultMosaic = expressionMosaic.Compile()(5, 2);
Console.WriteLine($"func:{ResultLambda}");
Console.WriteLine($"expression:{ResultExpression}");
Console.WriteLine($"expressionMosaic:{ResultMosaic}");
View Code

下面舉例說明以下Expression.Block

ParameterExpression varExpr = Expression.Variable(typeof(int), "x"); //add(int x);
var ex1 = Expression.Assign(varExpr, Expression.Constant(1)); //x = 1; var ex1 = x;
var ex2 = Expression.Add(ex1, Expression.Constant(5)); //var ex2 = ex1 + 5;//6
var ex4 = Expression.Add(ex2, Expression.Constant(9)); //var ex4 = ex2 + 9; //15
var ex5 = Expression.Add(ex4, Expression.Constant(8)); // var ex5 = ex4 + 8; //23
BlockExpression blockExpr = Expression.Block(
    new ParameterExpression[] { varExpr },
    ex1,
    ex2,
    ex4,
    ex5
);
View Code

該代碼等效於,返回的結果都以最后一個Expression為主,則為ex5這個表達式

public int add(int x)
{
    x = 1;
    var ex1 = x;
    var ex2 = ex1 + 5;//6
    var ex4 = ex2 + 9; //15
    var ex5 = ex4 + 8; //23
    return ex5; //23
}
View Code

Expression.Block沒有返回值

{   
    Expression A = Expression.Constant("第一大");
    Expression B = Expression.Constant("第二大");
    Expression ex = Expression.GreaterThan(Expression.Constant(1), Expression.Constant(2));

    var method = typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) });
    var AM = Expression.Call(method, A);
    var BM = Expression.Call(method, B);

    var condition = Expression.IfThenElse(ex, AM, BM);
    var blockExpr = Expression.Block(condition); //IfThenElse是沒有返回值的

    foreach (var expr in blockExpr.Expressions)
        Console.WriteLine(expr.ToString());

    var lambdaExpression = Expression.Lambda<Action>(blockExpr).Compile();
    lambdaExpression();
}
View Code

下圖是Expression的一些變量

 

 

 

 二:表達式目錄樹與委托

Expression一般都是都是配合委托一起來使用的,比如和委托Action(沒有返回值),Func(至少有一個返回參數,且最后一個值為返回參數),Action,Func既可以直接傳入一個與之匹配的實體方法,又可以傳入lambda表達式這種匿名類(這種是聲明lambda表達式的一種快捷方式)。Expression,Action,Func關鍵詞是在.net 3.5之后出現的。Expression<Func<>>是可以轉成Func的(通過compile()這個方法轉換)。反過來則不行。我們可以理解為Func<>經過定義后,就無法改變它了。而表達式樹(Expression<Func<>>則是可以進行變更的。Lambda使用lambda表達聲明表達式目錄樹的時候注意不能有{},即:

Func<int, int, int> func = (m, n) => m * n + 2;
View Code

上面這樣是可以的。但是下面這樣是不被允許的:

 Expression<Func<int, int, int>> exp1 = (m, n) =>
  {
          return m * n + 2;
  };//不能有語句體   只能是一行,不能有大括號
View Code

下面的例子來解析一下委托和表達式目錄樹

#region PrivateMethod
 private static void Do1(Func<People, bool> func)
 {
     List<People> people = new List<People>();
     people.Where(func);
 }
 private static void Do1(Expression<Func<People, bool>> func)
 {
     List<People> people = new List<People>()
     {
         new People(){Id=4,Name="123",Age=4},
         new People(){Id=5,Name="234",Age=5},
         new People(){Id=6,Name="345",Age=6},
     };

     List<People> peopleList = people.Where(func.Compile()).ToList();
 }

 private static IQueryable<People> GetQueryable(Expression<Func<People, bool>> func)
 {
     List<People> people = new List<People>()
     {
         new People(){Id=4,Name="123",Age=4},
         new People(){Id=5,Name="234",Age=5},
         new People(){Id=6,Name="345",Age=6},
     };

     return people.AsQueryable<People>().Where(func);
 }
 #endregion
View Code

然后調用的時候為如下:

Expression<Func<People, bool>> lambda1 = x => x.Age > 5;
Expression<Func<People, bool>> lambda2 = x => x.Id > 5;
Expression<Func<People, bool>> lambda3 = lambda1.And(lambda2);
Expression<Func<People, bool>> lambda4 = lambda1.Or(lambda2);
Expression<Func<People, bool>> lambda5 = lambda1.Not();
Do1(lambda3);
Do1(lambda4);
Do1(lambda5);
View Code

 

三:使用Expression來進行不同對象的相同名字的屬性映射

如果我們有一個新的對象和People屬性基本上一致,如下:

/// <summary>
/// 實體類Target
/// PeopleDTO
/// </summary>
public class PeopleCopy
{

    public int Age { get; set; }
    public string Name { get; set; }
    public int Id;
}
View Code

現在我們想要把People的中Age,Name,Id等賦值給PeopleCopy,第一種我們直接想到的是硬編碼,然后如下:

People people = new People()
{
    Id = 11,
    Name = "加菲貓",
    Age = 31
};
//PeopleCopy copy = (PeopleCopy)people; //這種強制轉換肯定是不行的

PeopleCopy peopleCopy = new PeopleCopy()
{
    Id = people.Id,
    Name = people.Name,
    Age = people.Age
};
View Code

但是如果有多個類型轉換,要寫N次,然后不同用且費力,所以我們會想到通用的方法,比如使用:【反射】,【序列化反序列化】,【緩存+表達式目錄】,【泛型+表達式目錄】,【AutoMapper】,我們可以用這五種方法都小試一下!

1:反射完成對象屬性映射

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ExpressionDemo.MappingExtend
{
    public class ReflectionMapper
    {
        /// <summary>
        /// 反射
        /// </summary>
        /// <typeparam name="TIn"></typeparam>
        /// <typeparam name="TOut"></typeparam>
        /// <param name="tIn"></param>
        /// <returns></returns>
        public static TOut Trans<TIn, TOut>(TIn tIn)
        {
            TOut tOut = Activator.CreateInstance<TOut>();
            foreach (var itemOut in tOut.GetType().GetProperties())
            {
                var propIn = tIn.GetType().GetProperty(itemOut.Name);
                itemOut.SetValue(tOut, propIn.GetValue(tIn));
            }
            foreach (var itemOut in tOut.GetType().GetFields())
            {
                var fieldIn = tIn.GetType().GetField(itemOut.Name);
                itemOut.SetValue(tOut, fieldIn.GetValue(tIn));
            }
            return tOut;
        }
    }
}
View Code

2:使用序列化和反序列化來完成對象屬性映射:

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ExpressionDemo.MappingExtend
{
    /// <summary>
    /// 使用第三方序列化反序列化工具
    /// 
    /// 還有automapper
    /// </summary>
    public class SerializeMapper
    {
        /// <summary>
        /// 序列化反序列化方式
        /// </summary>
        /// <typeparam name="TIn"></typeparam>
        /// <typeparam name="TOut"></typeparam>
        public static TOut Trans<TIn, TOut>(TIn tIn)
        {
            return JsonConvert.DeserializeObject<TOut>(JsonConvert.SerializeObject(tIn));
        }
    }
}
View Code

3:緩存+表達式目錄樹

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace ExpressionDemo.MappingExtend
{
    /// <summary>
    /// 生成表達式目錄樹 緩存
    /// </summary>
    public class ExpressionMapper
    {
        /// <summary>
        /// 字典緩存--hash分布
        /// </summary>
        private static Dictionary<string, object> _Dic = new Dictionary<string, object>();

        /// <summary>
        /// 字典緩存表達式樹
        /// </summary>
        /// <typeparam name="TIn"></typeparam>
        /// <typeparam name="TOut"></typeparam>
        /// <param name="tIn"></param>
        /// <returns></returns>
        public static TOut Trans<TIn, TOut>(TIn tIn)
        {
            string key = string.Format("funckey_{0}_{1}", typeof(TIn).FullName, typeof(TOut).FullName);
            if (!_Dic.ContainsKey(key))
            {
                ParameterExpression parameterExpression = Expression.Parameter(typeof(TIn), "p");
                List<MemberBinding> memberBindingList = new List<MemberBinding>();
                foreach (var item in typeof(TOut).GetProperties())
                {
                    MemberExpression property = Expression.Property(parameterExpression, typeof(TIn).GetProperty(item.Name));
                    MemberBinding memberBinding = Expression.Bind(item, property);
                    memberBindingList.Add(memberBinding);
                }
                foreach (var item in typeof(TOut).GetFields())
                {
                    MemberExpression property = Expression.Field(parameterExpression, typeof(TIn).GetField(item.Name));
                    MemberBinding memberBinding = Expression.Bind(item, property);
                    memberBindingList.Add(memberBinding);
                }
                MemberInitExpression memberInitExpression = Expression.MemberInit(Expression.New(typeof(TOut)), memberBindingList.ToArray());
                Expression<Func<TIn, TOut>> lambda = Expression.Lambda<Func<TIn, TOut>>(memberInitExpression, new ParameterExpression[]
                {
                    parameterExpression
                });
                Func<TIn, TOut> func = lambda.Compile();//拼裝是一次性的
                _Dic[key] = func;
            }
            return ((Func<TIn, TOut>)_Dic[key]).Invoke(tIn);
        }
    }
}
View Code

4:泛型+表達式目錄樹

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

namespace ExpressionDemo.MappingExtend
{
    /// <summary>
    /// 生成表達式目錄樹  泛型緩存
    /// </summary>
    /// <typeparam name="TIn"></typeparam>
    /// <typeparam name="TOut"></typeparam>
    public class ExpressionGenericMapper<TIn, TOut>//Mapper`2
    {
        private static Func<TIn, TOut> _FUNC = null;
        static ExpressionGenericMapper()
        {
            ParameterExpression parameterExpression = Expression.Parameter(typeof(TIn), "p");
            List<MemberBinding> memberBindingList = new List<MemberBinding>();
            foreach (var item in typeof(TOut).GetProperties())
            {
                MemberExpression property = Expression.Property(parameterExpression, typeof(TIn).GetProperty(item.Name)); //p.Age
                MemberBinding memberBinding = Expression.Bind(item, property); //Age=p.Age
                memberBindingList.Add(memberBinding);
            }
            foreach (var item in typeof(TOut).GetFields())
            {
                MemberExpression property = Expression.Field(parameterExpression, typeof(TIn).GetField(item.Name));
                MemberBinding memberBinding = Expression.Bind(item, property);
                memberBindingList.Add(memberBinding);
            }
            //new PeopleCopy() {Age = p.Age, Name = p.Name, Id = p.Id}
            MemberInitExpression memberInitExpression = Expression.MemberInit(Expression.New(typeof(TOut)), memberBindingList.ToArray());
            //p => new PeopleCopy() {Age = p.Age, Name = p.Name, Id = p.Id}
            Expression<Func<TIn, TOut>> lambda = Expression.Lambda<Func<TIn, TOut>>(memberInitExpression, new ParameterExpression[]
            {
                    parameterExpression
            });
            _FUNC = lambda.Compile();//拼裝是一次性的
        }
        public static TOut Trans(TIn t)
        {
            return _FUNC(t);
        }
    }
}
View Code

5:使用.netFramwork框架自帶的AutoMapper,首先我們要nuget添加引用AutoMapper即可直接使用,具體代碼為:

using AutoMapper;

namespace ExpressionDemo.MappingExtend
{
    public class AutoMapperTest
    {
        public static TOut Trans<TIn, TOut>(TIn tIn)
        {
            return Mapper.Instance.Map<TOut>(tIn);
        }
    }
}
View Code

五種方法我們分別調用一下,然后測試一下性能,代碼如下:

{
                People people = new People()
                {
                    Id = 11,
                    Name = "加菲貓",
                    Age = 31
                };
                //使用AutoMapper之前必須要初始化對應的關系
                Mapper.Initialize(x => x.CreateMap<People, PeopleCopy>()); 
               
                long common = 0;
                long generic = 0;
                long cache = 0;
                long reflection = 0;
                long serialize = 0;
                long autoMapper = 0;
                {
                    Stopwatch watch = new Stopwatch();
                    watch.Start();
                    for (int i = 0; i < 1000000; i++)
                    {
                        PeopleCopy peopleCopy = new PeopleCopy()
                        {
                            Id = people.Id,
                            Name = people.Name,
                            Age = people.Age
                        };
                    }
                    watch.Stop();
                    common = watch.ElapsedMilliseconds;
                }
                {
                    Stopwatch watch = new Stopwatch();
                    watch.Start();
                    for (int i = 0; i < 1000000; i++)
                    {
                        PeopleCopy peopleCopy = AutoMapperTest.Trans<People, PeopleCopy>(people);
                    }
                    watch.Stop();
                    autoMapper = watch.ElapsedMilliseconds;
                }
                {
                    Stopwatch watch = new Stopwatch();
                    watch.Start();
                    for (int i = 0; i < 1000000; i++)
                    {
                        PeopleCopy peopleCopy = ReflectionMapper.Trans<People, PeopleCopy>(people);
                    }
                    watch.Stop();
                    reflection = watch.ElapsedMilliseconds;
                }
                {
                    Stopwatch watch = new Stopwatch();
                    watch.Start();
                    for (int i = 0; i < 1000000; i++)
                    {
                        PeopleCopy peopleCopy = SerializeMapper.Trans<People, PeopleCopy>(people);
                    }
                    watch.Stop();
                    serialize = watch.ElapsedMilliseconds;
                }
                {
                    Stopwatch watch = new Stopwatch();
                    watch.Start();
                    for (int i = 0; i < 1000000; i++)
                    {
                        PeopleCopy peopleCopy = ExpressionMapper.Trans<People, PeopleCopy>(people);
                    }
                    watch.Stop();
                    cache = watch.ElapsedMilliseconds;
                }
                {
                    Stopwatch watch = new Stopwatch();
                    watch.Start();
                    for (int i = 0; i < 1000000; i++)
                    {
                        PeopleCopy peopleCopy = ExpressionGenericMapper<People, PeopleCopy>.Trans(people);
                    }
                    watch.Stop();
                    generic = watch.ElapsedMilliseconds;
                }

                Console.WriteLine($"common = { common} ms");
                Console.WriteLine($"reflection = { reflection} ms");
                Console.WriteLine($"serialize = { serialize} ms");
                Console.WriteLine($"cache = { cache} ms");
                Console.WriteLine($"generic = { generic} ms");
                Console.WriteLine($"automapper = { autoMapper} ms");
                //性能比automapper還要高
            }
View Code

運行結果如下:

 

通過結果發現:反射和序列化運用的時間最多,而我們驚奇的發現表達式目錄樹+泛型緩存比框架自帶的AutoMapper時間還短!有木有感覺超級膩害~!

 

四:ORM與表達式樹目錄的關系

我們平常項目中經常用到EF,其實都是繼承Queryable,然后我們使用的EF通常都會使用 var items = anserDo.GetAll().Where(x => x.OrganizationId == input.oid || input.oid == 0) ,where其實傳的就是表達式目錄樹。那我們來一步一步解析EF底層實現的具體邏輯。

lambada表達式上面說了能使用Expression來動態拼接,當然它還有一個神奇的功能,能動態的解耦。Expression有個類ExpressionVisitor

 

 

 

 這個類中的Visit(Expression node)是解讀表達式的入口,然后能夠神奇的區分參數和方法體,然后將表達式調度到此類中更專用的訪問方法中,然后一層一層的解析下去,一直到最終的葉節點!

將表達式調度到此類中更專用的訪問方法中:我們來舉例說明:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace ExpressionDemo.Visitor
{
    public class OperationsVisitor : ExpressionVisitor
    {
        public Expression Modify(Expression expression)
        {
            return this.Visit(expression);
        }

        protected override Expression VisitBinary(BinaryExpression b)
        {
            if (b.NodeType == ExpressionType.Add)
            {
                Expression left = this.Visit(b.Left);
                Expression right = this.Visit(b.Right);
                return Expression.Subtract(left, right);
            }

            return base.VisitBinary(b);
        }

        protected override Expression VisitConstant(ConstantExpression node)
        {
            return base.VisitConstant(node);
        }
    }
}
View Code

下面調用:

1 {
2     //修改表達式目錄樹
3     Expression<Func<int, int, int>> exp = (m, n) => m * n + 2;
4     OperationsVisitor visitor = new OperationsVisitor();      
5     Expression expNew = visitor.Modify(exp);
6 }
View Code

visit這個這個方法能夠識別出來 m*n+2 是個二叉樹,會通過下面的圖然后一步一步的進行解析,如果遇到m*n 這會直接調用VisitBinary(BinaryExpression b)這個方法,如果遇到m或者n會調用VisitParameter(ParameterExpression node)這個方法,

如果遇到2常量則會調用VisitConstant(ConstantExpression node),這就是visit神奇的調度功能!

 

 

我們EF寫的where等lambda表達式,就是通過ExpressionVisitor這個類來反解析的!之前沒有學習過表達式目錄樹,以為ef本來就應該這樣寫,有沒有和我一樣認為的?

我們現在模擬寫一個lambda轉換sql的方法

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

namespace ExpressionDemo.Visitor
{
    public class ConditionBuilderVisitor : ExpressionVisitor
    {
        private Stack<string> _StringStack = new Stack<string>();

        public string Condition()
        {
            string condition = string.Concat(this._StringStack.ToArray());
            this._StringStack.Clear();
            return condition;
        }

        /// <summary>
        /// 如果是二元表達式
        /// </summary>
        /// <param name="node"></param>
        /// <returns></returns>
        protected override Expression VisitBinary(BinaryExpression node)
        {
            if (node == null) throw new ArgumentNullException("BinaryExpression");

            this._StringStack.Push(")");
            base.Visit(node.Right);//解析右邊
            this._StringStack.Push(" " + node.NodeType.ToSqlOperator() + " ");
            base.Visit(node.Left);//解析左邊
            this._StringStack.Push("(");

            return node;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="node"></param>
        /// <returns></returns>
        protected override Expression VisitMember(MemberExpression node)
        {
            if (node == null) throw new ArgumentNullException("MemberExpression");
            this._StringStack.Push(" [" + node.Member.Name + "] ");
            return node;
        }
        /// <summary>
        /// 常量表達式
        /// </summary>
        /// <param name="node"></param>
        /// <returns></returns>
        protected override Expression VisitConstant(ConstantExpression node)
        {
            if (node == null) throw new ArgumentNullException("ConstantExpression");
            this._StringStack.Push(" '" + node.Value + "' ");
            return node;
        }
        /// <summary>
        /// 方法表達式
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        protected override Expression VisitMethodCall(MethodCallExpression m)
        {
            if (m == null) throw new ArgumentNullException("MethodCallExpression");

            string format;
            switch (m.Method.Name)
            {
                case "StartsWith":
                    format = "({0} LIKE {1}+'%')";
                    break;

                case "Contains":
                    format = "({0} LIKE '%'+{1}+'%')";
                    break;

                case "EndsWith":
                    format = "({0} LIKE '%'+{1})";
                    break;

                default:
                    throw new NotSupportedException(m.NodeType + " is not supported!");
            }
            this.Visit(m.Object);
            this.Visit(m.Arguments[0]);
            string right = this._StringStack.Pop();
            string left = this._StringStack.Pop();
            this._StringStack.Push(String.Format(format, left, right));

            return m;
        }
    }
}
View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace ExpressionDemo.DBExtend
{
    internal static class SqlOperator
    {
        internal static string ToSqlOperator(this ExpressionType type)
        {
            switch (type)
            {
                case (ExpressionType.AndAlso):
                case (ExpressionType.And):
                    return "AND";
                case (ExpressionType.OrElse):
                case (ExpressionType.Or):
                    return "OR";
                case (ExpressionType.Not):
                    return "NOT";
                case (ExpressionType.NotEqual):
                    return "<>";
                case ExpressionType.GreaterThan:
                    return ">";
                case ExpressionType.GreaterThanOrEqual:
                    return ">=";
                case ExpressionType.LessThan:
                    return "<";
                case ExpressionType.LessThanOrEqual:
                    return "<=";
                case (ExpressionType.Equal):
                    return "=";
                default:
                    throw new Exception("不支持該方法");
            }

        }
    }
}
View Code

然后調用的時候如下:

{
    //修改表達式目錄樹
    Expression<Func<int, int, int>> exp = (m, n) => m * n + 2;
    OperationsVisitor visitor = new OperationsVisitor();               
    Expression expNew = visitor.Modify(exp);
}

{
    Expression<Func<People, bool>> lambda = x => x.Age > 5 && x.Id > 5
                                             && x.Name.StartsWith("1")
                                             && x.Name.EndsWith("1")
                                             && x.Name.Contains("1");

    string sql = string.Format("Delete From [{0}] WHERE {1}"
        , typeof(People).Name
        , " [Age]>5 AND [ID] >5"
        );
    ConditionBuilderVisitor vistor = new ConditionBuilderVisitor();
    vistor.Visit(lambda);
    Console.WriteLine(vistor.Condition());
}
{
    Expression<Func<People, bool>> lambda = x => x.Age > 5 && x.Name == "A" || x.Id > 5;
    ConditionBuilderVisitor vistor = new ConditionBuilderVisitor();
    vistor.Visit(lambda);
    Console.WriteLine(vistor.Condition());
}
{
    Expression<Func<People, bool>> lambda = x => x.Age > 5 || (x.Name == "A" && x.Id > 5);
    ConditionBuilderVisitor vistor = new ConditionBuilderVisitor();
    vistor.Visit(lambda);
    Console.WriteLine(vistor.Condition());
}
{
    Expression<Func<People, bool>> lambda = x => (x.Age > 5 || x.Name == "A") && x.Id > 5;
    ConditionBuilderVisitor vistor = new ConditionBuilderVisitor();
    vistor.Visit(lambda);
    Console.WriteLine(vistor.Condition());
}
View Code

目前Expression只支持ExpressionType的84種操作符Add, AndAlso等等,然后VisitMethodCall這個方法中表示lambda能解析出來的方法名字,如果需要可以自行修改會得到對應的sql語句的where條件!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM