在 Roslyn 中添加模块作为参考 [英] Add module as reference in Roslyn
问题描述
我正在尝试使用 Roslyn Microsoft.Codeanalysis 库实现以下基于 csc 命令的编译
I'm trying to implement following csc command based compilation with the Roslyn Microsoft.Codeanalysis library
csc /target:library /out:UserControlBase.dll UserControlBase.cs /addmodule:"c:\artifacts\MyLib.netmodule"
以下是与 Roslyn 相同的实现
Following is the implementation of the same with Roslyn
var compilation = await project.GetCompilationAsync();
//Add Module
compilation.AddReferences(ModuleMetadata.CreateFromFile(@"c:\artifacts\MyLib.netmodule").GetReference());
compilationStatus = compilation.Emit(outputFolderPath + @"\Test1.dll", outputFolderPath + @"\Test1.pdb");
if (!compilationStatus.Success)
{
foreach (var item in compilationStatus.Diagnostics)
{
Console.WriteLine(item);
}
}
问题:由于未从 netmodule 解析引用,.Netmodule 未添加到项目中并且编译失败.
Issue: .Netmodule is not getting added to the project and compilation failed due to references not resolved from netmodule.
有谁知道添加这个的正确方法吗?
Does anyone know the correct way to add this?
我使用的是 Microsoft.CodeAnalysis 1.0.0
I'm using Microsoft.CodeAnalysis 1.0.0
推荐答案
我知道这有点旧,但答案可能对其他人有用.
I know this is a little old, but the answer could be useful to someone else.
Roslyn 中的一切都是不可变的.因此,调用 compiler.AddReference 不会添加对您拥有的编译对象的引用,而是基于原始对象创建一个新的编译对象,并带有其他引用.
Everything in Roslyn is immutable. So, calling compilation.AddReference doesn't add the reference to the compilation object you have, but instead creates a new compilation object based on the original, with the additional references.
因此,要使其工作,您需要在 AddReference 调用返回的对象中调用 Emit.你可以只替换编译变量:
so, for this to work you need to call Emit in the object returned by the AddReference call. You could just replace the compilation variable:
compilation = compilation.AddReferences(ModuleMetadata.CreateFromFile(@"c:\artifacts\MyLib.netmodule").GetReference());
或者使用一个新变量并从中调用 Emit:
or use a new variable and call Emit from that:
var compWithRefs = compilation.AddReferences(ModuleMetadata.CreateFromFile(@"c:\artifacts\MyLib.netmodule").GetReference());
compilationStatus = compWithRefs.Emit(outputFolderPath + @"\Test1.dll", outputFolderPath + @"\Test1.pdb");
这篇关于在 Roslyn 中添加模块作为参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!