从 cs 文件加载脚本并访问主机方法、属性等? [英] Loading a script from a cs file and accessing host methods, properties etc?
问题描述
我只是想和 Roslyn 一起玩,但不确定如何执行以下操作.
I'm just having a play with Roslyn but unsure on how to do the following.
为了简单起见,假设我有一个主机程序,它具有这样的方法
To keep this simple, lets say I have a host program which has a method like so
public void DisplayMessage(string message)
{
MessageBox.Show(message);
}
然后我可以有一个名为 MyScript.csx 的脚本文件,然后在脚本中的某处有类似的东西
Can I then have a script file called MyScript.csx and then somewhere in the script have something like
void Main()
{
Host.DisplayMessage("I am a script");
}
然后我让主机加载文件并执行它.
Then I have the host load the file and execute it.
如果这种事情做不到,有没有基于c#的脚本系统/引擎可以做到?这些是要求
If this sort of thing can't be done, is there a scripting system/engine based on c# that can do it? These are the requirements
- 宿主应用程序可以从文件加载脚本.
- 脚本文件是用 c# 编写的,因此可以使用 VS2010 和语法等编写
- 脚本文件可以访问主机公共方法、属性等
推荐答案
是的,您可以使用 Roslyn 做您想做的事.
Yes, you can do what you want using Roslyn.
首先,创建一个具有公共 DisplayMessage
方法的公共 Host
类(或使用现有类).然后创建 ScriptEngine
,指定包含 Host
的程序集作为引用.之后,您可以对您的文件调用 ExecuteFile()
,将 Host
对象作为另一个参数:
First, create a public Host
class that has a public DisplayMessage
method (or use a existing class). Then create ScriptEngine
, specifying the assembly that contains Host
as a reference. After that, you can call ExecuteFile()
on your file, with the Host
object as another parameter:
var engine = new ScriptEngine(references: new[] { typeof(Host).Assembly });
engine.ExecuteFile("MyScript.csx", new Host());
脚本文件不需要任何Main()
方法,直接调用宿主对象的方法:
The script files doesn't need any Main()
method, and you call the method on the host object directly:
DisplayMessage("I am a script");
这篇关于从 cs 文件加载脚本并访问主机方法、属性等?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!