.Net Core 1.0中的运行时编译和运行代码

编程入门 行业动态 更新时间:2024-10-25 02:26:11
本文介绍了.Net Core 1.0中的运行时编译和运行代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

是否可以在新的.Net Core(更好的.Net Standard Platform)中在运行时编译和运行C#代码?我已经看到了一些示例(.Net Framework),但是它们使用了与netcoreapp1.0(.NETCoreApp,Version = v1.0)不兼容的NuGet软件包

Is it possible to compile and run C# code at runtime in the new .Net Core (better .Net Standard Platform)? 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 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="www.myget/F/roslyn-nightly/api/v3/index.json" /> </packageSources> </configuration>

  • 将以下软件包作为依赖项添加到project.json(注意,这是从今天开始的软件包,您需要ent版本):

  • 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,尽管如此,罗斯林仍然使用):

    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中的运行时编译和运行代码

    本文发布于:2023-11-15 23:21:19,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1598861.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:代码   Net   Core

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!