是否有可能在新的.Net核心(更好的.Net标准平台)中运行时编译和运行c#代码?我见过一些例子(.Net框架),但使用的NuGet包有在.Net核心1.0中运行时编译和运行代码
不兼容netcoreapp1.0(.NETCoreApp,版本= V1.0)
是否有可能在新的.Net核心(更好的.Net标准平台)中运行时编译和运行c#代码?我见过一些例子(.Net框架),但使用的NuGet包有在.Net核心1.0中运行时编译和运行代码
不兼容netcoreapp1.0(.NETCoreApp,版本= V1.0)
选项#1:使用完整的C#编译器编译程序集,加载它,然后从中执行一个方法。
这需要以下软件包,如您project.json依赖关系:
"Microsoft.CodeAnalysis.CSharp": "1.3.0-beta1-20160429-01",
"System.Runtime.Loader": "4.0.0-rc2-24027",
然后你可以使用这样的代码:
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:使用罗斯林脚本。这将导致更简单的代码,但目前需要更多的设置:
创建NuGet.config从罗斯林夜间进得包:
<?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(请注意,这是包从今天起,您将需要在未来不同的版本):
"Microsoft.CodeAnalysis.CSharp.Scripting": "1.3.0-beta1-20160530-01",
您还需要导入dotnet
(过时的 “目标框架名字对象”,which is nevertheless still used by Roslyn):
"frameworks": {
"netcoreapp1.0": {
"imports": "dotnet5.6"
}
}
现在你终于可以使用脚本:
CSharpScript.EvaluateAsync(@"using System;Console.WriteLine(""Hello Roslyn."");").Wait();
只是增加@svick选择一个答案。如果您想保留在内存中的组件(而不是写入文件),可以使用下面的方法:
AssemblyLoadContext context = AssemblyLoadContext.Default;
Assembly assembly = context.LoadFromStream(ms);
这是不同的,在Net451其中的代码是:
Assembly assembly = Assembly.Load(ms.ToArray());
我代码同时针对Net451和Netstandard,所以我不得不使用指令来解决这个问题。完整的代码示例如下:
string code = CreateFunctionCode();
var syntaxTree = CSharpSyntaxTree.ParseText(code);
MetadataReference[] references = new MetadataReference[]
{
MetadataReference.CreateFromFile(typeof(object).GetTypeInfo().Assembly.Location),
MetadataReference.CreateFromFile(typeof(Hashtable).GetTypeInfo().Assembly.Location)
};
var compilation = CSharpCompilation.Create("Function.dll",
syntaxTrees: new[] { syntaxTree },
references: references,
options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
StringBuilder message = new StringBuilder();
using (var ms = new MemoryStream())
{
EmitResult result = compilation.Emit(ms);
if (!result.Success)
{
IEnumerable<Diagnostic> failures = result.Diagnostics.Where(diagnostic =>
diagnostic.IsWarningAsError ||
diagnostic.Severity == DiagnosticSeverity.Error);
foreach (Diagnostic diagnostic in failures)
{
message.AppendFormat("{0}: {1}", diagnostic.Id, diagnostic.GetMessage());
}
return new ReturnValue<MethodInfo>(false, "The following compile errors were encountered: " + message.ToString(), null);
}
else
{
ms.Seek(0, SeekOrigin.Begin);
#if NET451
Assembly assembly = Assembly.Load(ms.ToArray());
#else
AssemblyLoadContext context = AssemblyLoadContext.Default;
Assembly assembly = context.LoadFromStream(ms);
#endif
Type mappingFunction = assembly.GetType("Program");
_functionMethod = mappingFunction.GetMethod("CustomFunction");
_resetMethod = mappingFunction.GetMethod("Reset");
}
}
'.Net核心'中不存在AssemblyLoadContext' –
@AlexZhukovskiy AssemblyLoadContext只存在于.Net核心,在'System.Runtime.Loader'包中。 – svick
非常感谢! – Mottor
你能看到我的其他问题吗? http://stackoverflow.com/questions/37482955/how-can-i-use-net-core-class-library-netstandard-v1-5-int-net-framework-4 – Mottor
你的例子工作正常,但它是不可能用参数添加'ReadLine'或'WriteLine'。我在哪里可以获得有关重载和方法存在的文档?因为Console具有Write方法但没有任何ReadLine时非常奇怪。 –