Loading a script from a cs file and accessing host methods, properties etc?

喜夏-厌秋 提交于 2019-12-02 06:28:39

问题


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

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.

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

  1. Host application can load script from a file.
  2. Script file is written in c# and so can be written using VS2010 with syntax etc
  3. Script file can access host public methods, properties etc

回答1:


Yes, you can do what you want using Roslyn.

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

The script files doesn't need any Main() method, and you call the method on the host object directly:

DisplayMessage("I am a script");



回答2:


I wrote an Introduction to the Roslyn scripting API that covers most of what you're asking. The ScriptEngine type also has a ExecuteFile method that would be useful for what you're trying to do.

Disclaimer: I work for Microsoft on the Roslyn project.



来源:https://stackoverflow.com/questions/9939433/loading-a-script-from-a-cs-file-and-accessing-host-methods-properties-etc

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