我对ScriptCS有一点初学问题,但无法找到答案。我们希望使用ScriptCS动态扩展托管应用程序。为此,我们需要将参数传递给脚本并从脚本中获取值。我目前有一个示例控制台应用程序,我正在测试脚本执行:
Program.cs的
using ScriptCs.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ScriptCs.Contracts;
using ScriptCs;
using ScriptCs.Engine.Mono;
using ScriptCs.Engine.Roslyn;
using System.Diagnostics;
namespace ScriptCsPoc
{
class MainClass
{
public static void Main(string[] args)
{
var console = (IConsole)new ScriptConsole();
var logProvider = new ColoredConsoleLogProvider(LogLevel.Info, console);
var builder = new ScriptServicesBuilder(console, logProvider);
SetEngine(builder);
var services = builder.Build();
var executor = (ScriptExecutor)services.Executor;
executor.Initialize(Enumerable.Empty<string>(), Enumerable.Empty<IScriptPack>(), "Guten Tag aus der Konsole");
ExecuteLooseScript(executor);
ExecuteFile(executor);
ExecuteFileFromCommandLine();
}
public static void ExecuteLooseScript(ScriptExecutor executor)
{
var script = @"Console.WriteLine(""Hello from scriptcs"")";
executor.ExecuteScript(script);
}
public static void ExecuteFile(ScriptExecutor executor)
{
ScriptResult result = executor.Execute("HelloWorld.csx", "parameter");
Console.WriteLine("Done Script");
}
public static void ExecuteFileFromCommandLine()
{
Process cmd = new Process();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.RedirectStandardInput = true;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.StartInfo.CreateNoWindow = true;
cmd.StartInfo.UseShellExecute = false;
cmd.Start();
cmd.StandardInput.WriteLine("scriptcs HelloWorld.csx -- blubber");
cmd.StandardInput.Flush();
cmd.StandardInput.Close();
cmd.WaitForExit();
string standardOut = cmd.StandardOutput.ReadToEnd();
Console.WriteLine("Done Script");
}
static void SetEngine(ScriptServicesBuilder builder)
{
var useMono = Type.GetType("Mono.Runtime") != null;
if (useMono)
{
builder.ScriptEngine<MonoScriptEngine>();
}
else {
builder.ScriptEngine<CSharpScriptEngine>();
}
}
}
}
HelloWorld.csx
#load child/greeter.csx
var greeter = new Greeter();
if (Env.ScriptArgs.Count > 0)
greeter.Greet(Env.ScriptArgs[0]);
else
greeter.Greet("Inside Script");
greeter.csx
public class Greeter {
public void Greet(string message) {
Console.WriteLine(message);
}
}
我能够在Console(ExecuteFileFromCommandLine())的调用中调用脚本,但如果我使用ScriptExecutor-Class的实例,则传递的参数不可用在Env.ScriptArgs中。有谁知道,我怎样才能从ScriptExecutor-Class中获取参数?
亲切的问候
答案 0 :(得分:0)
好的,解决这个问题的方法是另外一个项目:
https://github.com/swn1/scriptcsambient
使用Scriptcsambient,可以轻松地将参数提供给ScriptCS-Script并从中获取值。
亲切的问候