* LambdaExpression繼承Expression ![](https://img2023.cnblogs.com/blog/2404061/202307/2404061-20230710110551773-2135938777.png) * Expression又繼承LambdaExpr ...
-
LambdaExpression繼承Expression
-
Expression
又繼承LambdaExpressio
所以,LambdaExpression與 Expression
註意:並非所有的Lambda表達式都能轉換成表達式樹。不能將帶有一個語句塊(即使只有一個return語句)的Lambda轉換成表達式樹,只有對單個表達式進行求值的lambda才可以。表達式中不能包含賦值操作,因為在表達式中表示不了這種操作。
形式一
//構建表達式樹
Expression<Func<double,double,double>> distanceCalc=(x,y)=>Math.Sqrt(x*x+y*y);
double distanceResult = distanceCalc.Compile()(3,4);
Console.WriteLine(distanceResult);
形式二
//手動實現Lambda表達式
//所需方法
var sqrtMethod = typeof(Math).GetMethod("Sqrt", new[] { typeof(double) }) ?? throw new InvalidOperationException("Math.Sqrt not found!");
//參數
var xParameter = Expression.Parameter(typeof(double), "x");
var yParameter = Expression.Parameter(typeof(double), "y");
var xSquared = Expression.Multiply(xParameter, xParameter);
var ySquared = Expression.Multiply(yParameter, yParameter);
var sum = Expression.Add(xSquared, ySquared);
//創建MethodCallExpression
var distance = Expression.Call(sqrtMethod, sum);
//將call轉換為lambda表達式
var distanceLambda = Expression.Lambda(
distance,
xParameter, yParameter);
var distanceFunc = (Func<double, double, double>)distanceLambda.Compile();
var res=distanceFunc(3, 4);
Console.WriteLine(res);
輸出結果