问题描述
我正在尝试将一些 .net 代码移植到新的 Core 运行时,但我在移植一些即时编译时遇到了麻烦.
I'm trying to port some .net code to the new Core runtime and I'm having a bad time porting some on-the-fly compilation.
要继续,它总是要求我提供 System.Runtime 和 mscorlib 的引用,但不知道如何引用它们.
To resume, it always asks me for a reference to System.Runtime and mscorlib, but have no clue on how to reference them.
顺便提一下,我不能引用 Framework 4.6,因为该项目必须发布到带有 .net Core 的 Linux 机器上.
As a side note, I can't reference Framework 4.6 as the project must be published to a Linux machine with .net Core.
这是最低代码:
string testClass = @"using System;
namespace test{
public class tes
{
public string unescape(string Text)
{
return Uri.UnescapeDataString(Text);
}
}
}";
var compilation = CSharpCompilation.Create(Guid.NewGuid().ToString() + ".dll")
.WithOptions(new CSharpCompilationOptions(Microsoft.CodeAnalysis.OutputKind.DynamicallyLinkedLibrary))
.AddReferences(
MetadataReference.CreateFromFile(typeof(Object).GetTypeInfo().Assembly.Location),
MetadataReference.CreateFromFile(typeof(Uri).GetTypeInfo().Assembly.Location)
)
.AddSyntaxTrees(CSharpSyntaxTree.ParseText(testClass));
var eResult = compilation.Emit("test.dll");
它总是抱怨需要 mscorlib(在本例中)和 System.Runtime(在我的实际项目中).
It always complains about the need of mscorlib (in this example) and System.Runtime (in my real project).
我使用的是 Microsoft.CodeAnalysis.CSharp 包版本 2.0.0-beta3
I'm using the Microsoft.CodeAnalysis.CSharp package version 2.0.0-beta3
关于如何使用 Roslyn 和 .net Core 即时编译的任何想法?
Any ideas on how to compile on the fly with Roslyn and .net Core?
推荐答案
好的,终于搞定了:
string testClass = @"using System;
namespace test{
public class tes
{
public string unescape(string Text)
{
return Uri.UnescapeDataString(Text);
}
}
}";
var dd = typeof(Enumerable).GetTypeInfo().Assembly.Location;
var coreDir = Directory.GetParent(dd);
var compilation = CSharpCompilation.Create(Guid.NewGuid().ToString() + ".dll")
.WithOptions(new CSharpCompilationOptions(Microsoft.CodeAnalysis.OutputKind.DynamicallyLinkedLibrary))
.AddReferences(
MetadataReference.CreateFromFile(typeof(Object).GetTypeInfo().Assembly.Location),
MetadataReference.CreateFromFile(typeof(Uri).GetTypeInfo().Assembly.Location),
MetadataReference.CreateFromFile(coreDir.FullName + Path.DirectorySeparatorChar + "mscorlib.dll"),
MetadataReference.CreateFromFile(coreDir.FullName + Path.DirectorySeparatorChar + "System.Runtime.dll")
)
.AddSyntaxTrees(CSharpSyntaxTree.ParseText(testClass));
var eResult = compilation.Emit("test.dll");
我不喜欢它,因为硬编码,但它似乎是让它工作的唯一方法.
I don't like it because the hardcoding, but it seems it's the only way to get it work.
这篇关于.net Core amd Roslyn CSharpCompilation,“对象"类型在未引用的程序集中定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!