Mono - 编译器即服务,如何创建编译类的实例

发布于 2025-01-06 07:39:26 字数 478 浏览 1 评论 0原文

我正在使用这个简单的程序:-

var evaluator = new Evaluator(
  new CompilerSettings(),
  new Report(new ConsoleReportPrinter()));

// Make it reference our own assembly so it can use IFoo
evaluator.ReferenceAssembly(typeof(IFoo).Assembly);

// Feed it some code
evaluator.Compile(
            @"
public class Foo : MonoCompilerDemo.IFoo
{
    public string Bar(string s) { return s.ToUpper(); }
}");

有没有办法,我可以在主程序中使用已编译类 foo 的实例。编译中存在需要委托的重载,但我无法理解它的用法

I am using this simple program :-

var evaluator = new Evaluator(
  new CompilerSettings(),
  new Report(new ConsoleReportPrinter()));

// Make it reference our own assembly so it can use IFoo
evaluator.ReferenceAssembly(typeof(IFoo).Assembly);

// Feed it some code
evaluator.Compile(
            @"
public class Foo : MonoCompilerDemo.IFoo
{
    public string Bar(string s) { return s.ToUpper(); }
}");

Is there a way , I can use the instance of compiled class foo with in the main program. There is overload in compile that takes a delegate, but I am unable to understand its usage

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

‖放下 2025-01-13 07:39:26

我一直在寻找类似的解决方案,但没有找到任何东西。直到我做了这样的事情......

Assembly asm = ((Type)evaluator.Evaluate("typeof(Foo);")).Assembly;
dynamic script = asm.CreateInstance("Foo");
script.Bar("hello")

给出这个带有简单程序的片段。 script.Bar("hello") 会产生“HELLO”

I was looking for a similar solution and had no luck finding anything. Until I did something like this...

Assembly asm = ((Type)evaluator.Evaluate("typeof(Foo);")).Assembly;
dynamic script = asm.CreateInstance("Foo");
script.Bar("hello")

Given this snippet with the simple program. script.Bar("hello") would produce "HELLO"

坐在坟头思考人生 2025-01-13 07:39:26

为什么不直接将此片段添加到您正在执行的代码中来编译您的类呢?

// define class Foo like you already did
return typeof(Foo);

然后

var type = (Type)evaluator.Compile(...
var myFooInstance = Activator.CreateInstance(type);

甚至更好的是,只需将“工厂方法”编译到您的代码中:)

// define class Foo like you already did
return new Func<IFoo>(() => new Foo());

然后在“外部”将返回的值转换回 Func 并使用它:

var fooFactory = (Func<IFoo>)evaluator.Compile(...
var instance = fooFactory();

Why not just add this fragment to the code you are executing to compile your class?

// define class Foo like you already did
return typeof(Foo);

and then

var type = (Type)evaluator.Compile(...
var myFooInstance = Activator.CreateInstance(type);

or even better, just compile a "factory method" into your code :)

// define class Foo like you already did
return new Func<IFoo>(() => new Foo());

and then "outside" you just cast the returned value back into a Func<IFoo> and use it:

var fooFactory = (Func<IFoo>)evaluator.Compile(...
var instance = fooFactory();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文