2014-05-13 7 views
5

Próbuję odtwarzać z podglądem użytkownika Roslyn i chciałbym wykonać prosty skrypt. Co chciałbym zrobić coś takiego jak:Jak uruchomić skrypt z Roslyn w Podglądzie użytkownika końcowego

static void Main(string[] args) 
{ 
    // Is this even valid? 
    var myScript = "int x = 5; int y = 6; x + y;"; 

    // What should I do here? 
    var compiledScript = Something.Compile(myScript); 
    var result = compiledScript.Execute(myScript); 


    Console.WriteLine(result); 
} 

Może ktoś punktu do niektórych zasobów i/lub powiedzieć, które Nuget pakiety zainstalować aby tak się stało. Zainstalowałem Microsoft.CodeAnalysis, ale nie wiem, czy to możliwe, ale czuję, że czegoś brakuje.

Odpowiedz

8

Skrypty API, które pozwalają to zrobić bardzo łatwo zostały (chwilowo) usunięte w najnowszym podglądzie. Nadal można skompilować skrypt, emitują i załadować montaż i powoływać się na swój punkt wejścia robiąc coś na wzór

public static class Program 
{ 
    public static void Main(string[] args) 
    { 
     var assemblyPath = Path.GetDirectoryName(typeof(object).Assembly.Location); 

     var defaultReferences = new[] { "mscorlib.dll", "System.dll", "System.Core.dll" }; 

     var script = @"using System; 
     public static class Program 
     { 
      public static void Main(string[] args) 
      { 
       Console.WriteLine(""Hello {0}"", args[0]); 
      } 
     }"; 

     // Parse the script to a SyntaxTree 
     var syntaxTree = CSharpSyntaxTree.ParseText(script); 

     // Compile the SyntaxTree to a CSharpCompilation 
     var compilation = CSharpCompilation.Create("Script", 
      new[] { syntaxTree }, 
      defaultReferences.Select(x => new MetadataFileReference(Path.Combine(assemblyPath, x))), 
      new CSharpCompilationOptions(OutputKind.ConsoleApplication)); 

     using (var outputStream = new MemoryStream()) 
     using (var pdbStream = new MemoryStream()) 
     { 
      // Emit assembly to streams. 
      var result = compilation.Emit(outputStream, pdbStream: pdbStream); 
      if (!result.Success) 
      { 
       return; 
      } 

      // Load the emitted assembly. 
      var assembly = Assembly.Load(outputStream.ToArray(), pdbStream.ToArray()); 

      // Invoke the entry point. 
      assembly.EntryPoint.Invoke(null, new object[] { new[] { "Tomas" } }); 
     } 
    } 
} 

To wyjście Hello Tomas w konsoli :)

+1

Musiałem zastąpić 'nowy MetadataFileReference' z' MetadataReference.CreateFromFile' w Roslyn wersja 1.0.0-beta1 – Rawling

2

Wydaje się, że w kwietniu 2014 r wydaniu scripting has been temporarily removed:

Co się stało z REPL i hostingu API skryptów?

Zespół dokonuje przeglądu projektów tych komponentów, które zostały wyświetlone w poprzednich wersjach CTP przed ponownym wprowadzeniem komponentów. Aktualnie zespół pracuje nad ukończeniem semantyki języka kodu interaktywnego/skryptowego.

+0

Dziękuję, oznaczony inną odpowiedź odkąd pokazał mi jak co najmniej :) –

Powiązane problemy