C#3.0 Expression Trees
C#3.0では何気にExpression Treesに興味があって弄っていたのですが、「Lambda Parameter not in scope」と例外が飛びまくって悩みました。
using System; using System.Linq; using System.Linq.Expressions; using System.Collections.Generic; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { // x => x * 2を手書きする #if false // 例外が発生 Expression<Func<int, int>> multi2 = Expression.Lambda<Func<int, int>>( Expression.Multiply(Expression.Parameter(typeof(int), "x"), Expression.Constant(2)), Expression.Parameter(typeof(int), "x")); // Lambda Parameter not in scope Console.WriteLine(multi2.Compile()(10)); #else // これならOK ParameterExpression x = Expression.Parameter(typeof(int), "x"); Expression<Func<int, int>> multi2 = Expression.Lambda<Func<int, int>>( Expression.Multiply(x, Expression.Constant(2)), x); Console.WriteLine(multi2.Compile()(10)); #endif } } }
ParameterExpressionの書き方が悪かった模様。前者みたいに書くのはダメだっけ?(^^;