2016-11-06 4 views
0

私は単純なIScriptインターフェイスを持っています。私はすべてのスクリプトがそれを実装するように強制したい。強制スクリプトインターフェイスを使用したRoslynスクリプト

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

私はこれをachiveするRoslyn scripting APIを使用したいです。このようなものは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!" 

答えて

1

タイプセーフは、(アプリケーションの)コンパイル時に強制される静的なものです。 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); 
} 
+0

おかげで行を変更します、答えます –

関連する問題