在 .NET Core 1.0 中在运行时编译和运行代码 [英] Compiling and running code at runtime in .NET Core 1.0

查看:26
本文介绍了在 .NET Core 1.0 中在运行时编译和运行代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在新的 .NET Core(更好的 .NET Standard 平台)中在运行时编译和运行 C# 代码?

Is it possible to compile and run C# code at runtime in the new .NET Core (better .NET Standard Platform)?

我看过一些示例(.NET Framework),但它们使用了与 netcoreapp1.0 不兼容的 NuGet 包(.NETCoreApp,Version=v1.0)

I have seen some examples (.NET Framework), but they used NuGet packages that are not compatible with netcoreapp1.0 (.NETCoreApp,Version=v1.0)

推荐答案

选项 #1:使用完整的 C# 编译器编译程序集,加载它,然后从中执行一个方法.

Option #1: Use the full C# compiler to compile an assembly, load it and then execute a method from it.

这需要以下包作为您的 project.json 中的依赖项:

This requires the following packages as dependencies in your project.json:

"Microsoft.CodeAnalysis.CSharp": "1.3.0-beta1-20160429-01",
"System.Runtime.Loader": "4.0.0-rc2-24027",

然后你可以使用这样的代码:

Then you can use code like this:

var compilation = CSharpCompilation.Create("a")
    .WithOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
    .AddReferences(
        MetadataReference.CreateFromFile(typeof(object).GetTypeInfo().Assembly.Location))
    .AddSyntaxTrees(CSharpSyntaxTree.ParseText(
        @"
using System;

public static class C
{
    public static void M()
    {
        Console.WriteLine(""Hello Roslyn."");
    }
}"));

var fileName = "a.dll";

compilation.Emit(fileName);

var a = AssemblyLoadContext.Default.LoadFromAssemblyPath(Path.GetFullPath(fileName));

a.GetType("C").GetMethod("M").Invoke(null, null);

选项 #2:使用 Roslyn 脚本.这将导致代码更简单,但目前需要更多设置:

Option #2: Use Roslyn Scripting. This will result in much simpler code, but it currently requires more setup:

  • 创建 NuGet.config 以从 Roslyn 夜间提要中获取包:

  • Create NuGet.config to get packages from the Roslyn nightly feed:

  <?xml version="1.0" encoding="utf-8"?>
  <configuration>
    <packageSources>
      <add key="Roslyn Nightly" value="https://www.myget.org/F/roslyn-nightly/api/v3/index.json" />
    </packageSources>
  </configuration>

  • 将以下包作为依赖添加到project.json(注意这是今天的包.你将来需要不同的版本):

  • Add the following package as a dependency to project.json (notice that this is package from today. You will need different version in the future):

      "Microsoft.CodeAnalysis.CSharp.Scripting": "1.3.0-beta1-20160530-01",
    

    您还需要导入 dotnet(过时的Target Framework Moniker",仍然被 Roslyn 使用):

    You also need to import dotnet (obsolete "Target Framework Moniker", which is nevertheless still used by Roslyn):

      "frameworks": {
        "netcoreapp1.0": {
          "imports": "dotnet5.6"
        }
      }
    

  • 现在您终于可以使用脚本了:

  • Now you can finally use Scripting:

      CSharpScript.EvaluateAsync(@"using System;Console.WriteLine(""Hello Roslyn."");").Wait();
    

  • 这篇关于在 .NET Core 1.0 中在运行时编译和运行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆