如何使用 Roslyn 解析所有正确的文件类型

How to parse all correct file types using Roslyn

所以我想在我的项目中加载所有 C# 文件,以便我可以使用 Roslyn 解析它们。

我想做这样的事情:

foreach(var file in project.Files.OfType<ROSLYN FILE TYPE HERE>())
{
... do something...
}

我怎样才能做到这一点。甚至有可能吗?

我已经做到了:

project.Files.Where(file=>Path.GetExtension(file.FilePath)=="cs")

但我不喜欢。谁有更好的主意?

您可以使用项目上的 Documents 属性 从项目中获取 C# 文件。 下面的扩展方法从给定项目中获取所有 C# 文件。

using Microsoft.CodeAnalysis;
using System.Collections.Generic;
using System.Linq;

static public IEnumerable<Document> CSFiles(this Project project) =>
    "C#" == project?.Language ?
    project?.Documents?.Where(Document => Document.SupportsSemanticModel) : null;