一个函数功能<>与罗斯林 [英] Create a Func<> with Roslyn

查看:202
本文介绍了一个函数功能<>与罗斯林的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

灵感<一href="http://weblogs.asp.net/lichen/archive/2013/10/08/delegate-performance-of-roslyn-sept-2012-ctp-is-im$p$pssive.aspx"相对=nofollow>这个和文章,我试图创造一个充满活力的功能与罗斯林。

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

然而 myFunc的总是空,我不能够确定问题所在。有人可以帮助我,使这个样品运行?

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?

推荐答案

免责声明:我还没有实际使用罗斯林在愤怒太大的所有

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

目前的code声明一个变量,但没有用它做任何事情之后。根据<一href="http://blog.filipekberg.se/2011/12/08/hosted-execution-of-smaller-$c$c-snippets-with-roslyn/">this随机博客帖子,它看起来像你可能只需要一个额外的前pression宣布后:

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 :)

这篇关于一个函数功能&LT;&GT;与罗斯林的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆