我正在创建一些Roslyn分析仪,它们使用该AdditionFiles
功能访问设置文件。我正在尝试测试分析仪是否正确使用此功能。
我有一种设置临时测试工作区的方法,并且我尝试通过两种途径添加其他文档:
private static Project CreateProject(IEnumerablesources) { var projectId = ProjectId.CreateNewId(TestProjectName); var solution = new AdhocWorkspace() .CurrentSolution .AddProject(projectId, TestProjectName, TestProjectName, LanguageNames.CSharp) .AddMetadataReference(projectId, CorlibReference) .AddMetadataReference(projectId, SystemCoreReference) .AddAdditionalDocument(DocumentInfo.Create(DocumentId.CreateNewId(projectId), "arnolyzer.yaml", filePath: @"..\..\arnolyzer.yaml")); var count = 0; foreach (var source in sources) { var newFileName = $"{DefaultFilePathPrefix}{count++}.{CSharpDefaultFileExt}"; var documentId = DocumentId.CreateNewId(projectId, newFileName); solution = solution.AddDocument(documentId, newFileName, SourceText.From(source)); } var settingsFileId = DocumentId.CreateNewId(projectId, "arnolyzer.yaml"); solution = solution.AddAdditionalDocument(settingsFileId, "arnolyzer.yaml", SourceText.From(@"..\..\arnolyzer.yaml")); return solution.GetProject(projectId); }
检查Project
实例,我可以看到已经添加了两个附加文档。
但是,在检查动作CompilationStartAnalysisContext.Options.AdditionalFiles
内时为空。AnalysisContext.RegisterCompilationStartAction
AdditionalFiles
有谁知道这种方法是否行得通,因此我在某处出错了?还是添加的其他文档Project
与AditionalFiles
功能无关?
这不会直接回答您的问题,但是您提到您正在尝试测试分析器是否使用附加文件。因此,这是我们解决该问题的方法:
var compilationWithAnalyzer = compilation.WithAnalyzers( diagnosticAnalyzers, new AnalyzerOptions(ImmutableArray.Create(new AnalyzerAdditionalFile(configuration.Path))), tokenSource.Token); var diagnostics = await compilationWithAnalyzer.GetAnalyzerDiagnosticsAsync();
在哪里AnalyzerAdditionalFile
延伸AdditionalText
:
public sealed class AnalyzerAdditionalFile : AdditionalText { private readonly string path; public AnalyzerAdditionalFile(string path) { this.path = path; } public override string Path => path; public override SourceText GetText(CancellationToken cancellationToken) { return SourceText.From(File.ReadAllText(path)); } }