c# - 使用 Roslyn 创建 Func<>

标签 c# .net roslyn

灵感来自 thisthis文章,我正在尝试使用 Roslyn 创建一个动态函数。

但是,上述来源已过时或不完整,我无法创建功能示例。到目前为止我的工作:

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();

但是 myFunc 始终为 null,我无法确定问题出在哪里。有人可以帮我运行这个示例吗?

最佳答案

免责声明:我实际上并没有在愤怒中使用 Roslyn。

目前您的代码声明了一个变量,但之后没有对它做任何事情。基于this random blog post ,看起来您可能只需要在声明后添加一个额外的表达式:

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

我不保证它会起作用,但试一试 :)

关于c# - 使用 Roslyn 创建 Func<>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22483213/

相关文章:

.net - 在 web.config 中加密连接字符串

c# - 系统.NullReferenceException : Object reference not set to an instance of an object in C#

c# - 在这种情况下,什么可以解释使用 const 的开销?

c# - CSharpCodeProvider在System.Collections.Generic下看不到Stack <T>类

.net - 多个部分意味着模型错误在表格之间流血

c# - 使用 Roslyn 2012 年 9 月 CTP 声明 var 变量

c# - 避免 VBCSCompiler 性能命中 Roslyn 支持的 ASP.NET Razor MVC View ?

c# - 在标签中获取 http 文件大小、下载位置和 URL

c# - 如何制作带注释的滚动条?