Expression -> Func. It works fine if I create a Func <> () me...">

Is there a way to set "DeclaringType" in the expression tree?

I am converting Func -> Expression -> Func. It works fine if I create a Func <> () method from a method (first example below), however, if I create a function using the expression tree (2nd example), it will end using the NullReferenceException when accessing func2.Method .DeclaringType.FullName. And that is because DeclaringType is NULL. (NJection uses reflection, so I think that's why it needs a DeclaringType.)

How can I populate the DeclaringType type for Func <> that was created by compiling the expression tree? (maybe this is not possible?) DeclaringType is set in the first example.

Using Func <> from method ... (works well)

// Build a Func<> Func<int, int> add = Add; // Convert it to an Expression using NJection Library Expression<Func<int, int>> expr = ToExpr<Func<int, int>>(add); // Convert it back to a Func<> Func < int, int> func = expr.Compile(); // Run the Func<> int result = func(100); 

Using the expression tree (doesn't work) ...

 // Build a Func<> using an Expression Tree ParameterExpression numParam = Expression.Parameter(typeof(int)); ConstantExpression five = Expression.Constant(5, typeof(int)); BinaryExpression numAddFive = Expression.Add(numParam, five); Func<int, int> func2 = Expression.Lambda<Func<int, int>>( numAddFive, new ParameterExpression[] { numParam }).Compile(); // Convert to an Expression using NJection (EXCEPTION ON NEXT LINE) // ToExpr is trying to access func2.Method.DeclaringType.FullName(DeclaringType is null) Expression<Func<int, int>> exp2 = ToExpr<Func<int, int>>(func2); // Convert it back to a Func<> Func<int, int> func2b = exp2.Compile(); // Run the Func<> int result2 = func2b(100); 
+6
source share
2 answers

I don’t know what the NJection library is used for, since their website is down and their Codeplex does not have source code.

If you just need to get an Expression that you can compile for a function, you can create it yourself. For instance. eg:

 static Expression<T> ToExpr<T>(T func) { var type = typeof(T); var method = type.GetMethod("Invoke"); // Delegate.Invoke() has parameters types matching delegate parameters types var pars = method.GetParameters() .Select(pi => Expression.Parameter(pi.ParameterType)) .ToArray(); return Expression.Lambda<T>( Expression.Call(Expression.Constant(func), method, pars), pars ); } 

With this ToExpr your above code compiles and runs without problems.

+3
source

I guess not.

Compiling an expression into an executable Func is a technically dynamic method. You can see this if you called func2.Method.GetType() . This returns a DynamicMethod type that is always null as a type declaration .

+2
source

All Articles