[英]Print the lambda passed to a Func object
我可以像這樣打印 lambda 表達式
Expression<Func<double,double>> expr = x => x * x;
string s = expr.ToString(); // "x => (x * x)"
然而,如果
Func<double, double> function = x => x * x;
那么如何生成Expression<Func<double,double>>
以產生相同的結果? 表達式構造函數是內部的,Func 類型和它們的表達式之間沒有隱式轉換。
你不能。
當你寫:
Expression<Action<int>> e = x => Console.WriteLine(x);
編譯器發出(簡化):
ParameterExpression parameterExpression = Expression.Parameter(typeof(int), "x");
MethodInfo method = typeof(Console).GetMethod("WriteLine", new[] { typeof(object) });
MethodCallExpression body = Expression.Call(null, method, parameterExpression);
Expression<Action<int>> e = Expression.Lambda<Action<int>>(body, parameterExpression);
看看它實際上是如何發出在運行時重新創建表達式樹的代碼的?
相反,當您編寫時:
Action<int> a = x => Console.WriteLine(x);
編譯器發出(簡化)
internal void GeneratedMethod(int x)
{
Console.WriteLine(x);
}
...
Action<int> a = new Action<int>(GeneratedMethod);
看到不同? 運行時根本無法采用已編譯的方法並為其創建表達式樹。
構建表達式樹的唯一方法是使用Expression
class 上的方法從各個部分構建它。 如果您使用 lambda,編譯器會巧妙地發出在運行時執行此操作的代碼。 但是,您不能從已編譯的方法開始。
請參閱SharpLab上的示例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.