我正在尝试使用roslyn的最终用户预览,并希望执行一个简单的脚本.我想做的是:
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);
}
Run Code Online (Sandbox Code Playgroud)
有人可以指向一些资源和/或告诉我要安装哪些nuget包来实现这一点.我已经安装了Microsoft.CodeAnalysis,但是无法弄清楚它是否可行,我觉得我错过了什么.
在最新预览中(暂时)删除了允许您轻松执行此操作的脚本API.您仍然可以编译脚本,发出并加载程序集,并通过执行某些操作来调用其入口点
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" } });
}
}
}
Run Code Online (Sandbox Code Playgroud)
它将Hello Tomas在控制台中输出:)
| 归档时间: |
|
| 查看次数: |
3269 次 |
| 最近记录: |