简体   繁体   English

Roslyn编译失败,但与Visual Studio一起使用

[英]Compilation fails with Roslyn, but works with Visual Studio

I'm trying to load an existing C# project and analyze one of its source files using Roslyn. 我正在尝试加载现有的C#项目并使用Roslyn分析其中一个源文件。 However, when compiling the source file, I get compilation errors which make no sense and are not present when compiling with Visual Studio. 但是,在编译源文件时,我得到的编译错误没有任何意义,在使用Visual Studio进行编译时不存在。 (the code also runs fine) (代码也运行正常)

Can anyone help me to diagnose this problem? 任何人都可以帮我诊断这个问题吗?

Parts of the code used to compile the file: 用于编译文件的部分代码:

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

The 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.

The solution consists of about 30 projects, the target project references some of these, and also some third parties, one of which contains the Vector3 . 该解决方案包含大约30个项目,目标项目引用其中一些项目,还有一些第三方,其中一个包含Vector3

I found a solution to this problem. 我找到了解决这个问题的方法。 One of the other projects i was referencing from my solution did not have any MetadataReferences loaded, so it was missing mscrolib. 我从我的解决方案中引用的其他项目之一没有加载任何MetadataReferences,因此它缺少mscrolib。 I think this causes the dependent project to throw these errors. 我认为这会导致依赖项目抛出这些错误。

As of why it was loading no MetadataReferences, I'm not entirely sure why it didn't load any. 至于为什么它没有加载MetadataReferences,我不完全确定为什么它没有加载任何。 I found that the csproj file had as a default configuration Debug|AnyCPU, which did not exist for this project, so i changed it to Debug|x86. 我发现csproj文件有一个默认配置Debug | AnyCPU,这个项目不存在,所以我把它改为Debug | x86。 It then loaded all references correctly and the compile errors i mentioned previously are gone now. 然后它正确加载所有引用,我之前提到的编译错误现在已经消失。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM