Create a Func<> with Roslyn

守給你的承諾、 提交于 2019-12-04 03:46:51

问题


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

However the mentioned sources are outdated or not complete and I'm not able to 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 myFunc is always null and I'm not able to identify where the problem is. Can someone help me out to make this sample run?


回答1:


Disclaimer: I haven't actually used Roslyn in anger much at all.

Currently your code declares a variable, but doesn't do anything with it afterwards. Based on this random blog post, it looks like you possibly just need an extra expression after the declaration:

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...

I don't guarantee it'll work, but give it a try :)



来源:https://stackoverflow.com/questions/22483213/create-a-func-with-roslyn

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!