使用 Roslyn 编译失败,但适用于 Visual Studio

Compilation fails with Roslyn, but works with Visual Studio

我正在尝试加载现有的 C# 项目并使用 Roslyn 分析其源文件之一。但是,在编译源文件时,我得到了没有意义的编译错误,并且在使用 Visual Studio 编译时不存在。 (代码也运行良好)

谁能帮我诊断这个问题?

用于编译文件的部分代码:

var oriSln = workspace.OpenSolutionAsync(@"absolutepath.sln").Result;
var oriProject = oriSln.Projects.First(p => p.Name == "projectname");
var doc = oriProject.GetDocument(docId);
var model = doc.GetSemanticModelAsync().Result;
var diag = model.GetDiagnostics(); // has strange errors

错误:

thefile.cs(36,68): error CS0518: Predefined type 'System.Void' is not defined or imported
thefile.cs(40,74): error CS0518: Predefined type 'System.Void' is not defined or imported
thefile.cs(40,50): error CS1503: Argument 1: cannot convert from 'float' to 'int'
thefile.cs(41,50): error CS1503: Argument 1: cannot convert from 'float' to 'int'
thefile.cs(51,50): error CS1503: Argument 2: cannot convert from 'float' to 'int'
thefile.cs(58,58): error CS1503: Argument 2: cannot convert from 'float' to 'int'
thefile.cs(130,40): error CS0518: Predefined type 'System.ValueType' is not defined or imported
thefile.cs(168,55): error CS0246: The type or namespace name 'Vector3' could not be found (are you missing a using directive or an assembly reference?)
thefile.cs(158,38): warning CS0168: The variable 'ex' is declared but never used
thefile.cs(7,1): hidden CS8019: Unnecessary using directive.
thefile.cs(6,1): hidden CS8019: Unnecessary using directive.

该解决方案由大约 30 个项目组成,目标项目引用了其中的一些以及一些第三方,其中一个包含 Vector3.

我找到了解决这个问题的方法。我从我的解决方案中引用的其他项目之一没有加载任何 MetadataReferences,因此它缺少 mscrolib。我认为这会导致依赖项目抛出这些错误。

至于为什么它没有加载任何 MetadataReferences,我不完全确定为什么它没有加载任何。我发现 csproj 文件有一个默认配置 Debug|AnyCPU,这个项目不存在,所以我将它更改为 Debug|x86。然后它正确加载了所有引用,我之前提到的编译错误现在消失了。