我正在尝试将一些代码移植到新的Core运行时中,而移植一些即时编译时却遇到了麻烦。
I'm trying to port some 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,因为必须将项目发布到具有 Core的Linux机器上。
As a side note, I can't reference Framework 4.6 as the project must be published to a Linux machine with 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和 Core进行即时编译的任何想法?
Any ideas on how to compile on the fly with Roslyn and Core?
推荐答案好,终于可以正常工作了:
Ok, got it finally working:
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和Roslyn CSharpCompilation,类型'Object'在未引用的程序集中定义
发布评论