问题
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
- Host application can load script from a file.
- Script file is written in c# and so can be written using VS2010 with syntax etc
- 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