Create Func <> with Roslyn

Inspired by this and this article , m is trying to create a dynamic function with Roslyn.

However, the mentioned sources are outdated or incomplete, and I cannot create a functional sample. My work so far:

var code = @"Func<int, int> doStuffToInt = i =>
{
   var result = i;
   for (var y = i; y <= i * 2; y++)
   {
      result += y;
   }
   return result;
};";


var se = new ScriptEngine();
var session = se.CreateSession();
session.AddReference(typeof(Program).Assembly);
session.AddReference(typeof(Expression).Assembly);

session.ImportNamespace("System");
session.ImportNamespace("System.Linq");
session.ImportNamespace("System.Linq.Expressions");

var submission = session.CompileSubmission<Func<int, int>>(code);

Func<int, int> myFunc =  submission.Execute();

However, myFuncit is always null, and I cannot determine where the problem is. Can someone help me to make this sample work?

+4
source share
1 answer

Disclaimer: I did not use Roslin at all in anger.

, . , , :

var code = @"Func<int, int> doStuffToInt = i =>
{
   var result = i;
   for (var y = i; y <= i * 2; y++)
   {
      result += y;
   }
   return result;
};
doStuffToInt"; // This is effectively the return statement for the script...

, , :)

+7

Source: https://habr.com/ru/post/1532314/


All Articles