具有强制脚本接口的 Roslyn 脚本

Roslyn scripting with enforced script interface

我有简单的 IScript 界面。我想强制所有脚本实现它。

public interface IScript<T>
{
    T Execute(object[] args);
}

我想使用 Roslyn scripting API to achive this. Something like this is possible with CSScript(参见 接口对齐)。

var code = @"
    using System;
    using My.Namespace.With.IScript;                

    public class Script : IScript<string>
    {
        public string Execute()
        {
            return ""Hello from script!"";
        }
    }
";

var script = CSharpScript.Create(code, ScriptOptions.Default);  // + Load all assemblies and references
script.WithInterface(typeof(IScript<string>));                  // I need something like this, to enforce interface
script.Compile();

string result =  script.Execute();                              // and then execute script

Console.WriteLine(result);                                      // print "Hello from script!"

类型安全是强制执行编译时间(您的应用程序)的静态事物。创建和 运行 CSharpScript 是在运行时完成的。所以你不能在运行时强制类型安全。

也许 CSharpScript 不是正确的方法。通过使用这个 SO 答案, You can compile a piece of C# code into memory and generate assembly bytes with Roslyn.

然后您将更改行

object obj = Activator.CreateInstance(type);

IScript<string> obj = Activator.CreateInstance(type) as IScript<string>;
if (obj != null) {
    obj.Execute(args);
}