c# - 从 SymbolAnalysisContext 获取语法树

标签 c# roslyn

我需要从给定的 SymbolAnalysisContext 访问语法树(完整的源文件文本)。我发现我可以调用 context.Compilation.SyntaxTrees 但从中选择哪一个?还有别的办法吗?

最佳答案

一个符号可以在一个或多个语法树中定义,或者在元数据中定义(通过引用)。您可以通过 ISymbol.Locations 获得所有这些,其中:

Gets the locations where the symbol was originally defined, either in source or metadata. Some symbols (for example, partial classes) may be defined in more than one location.

如果您只对源代码中定义的那些感兴趣,您可以这样做:

var syntaxTrees = from x in context.Symbol.Locations
                  where x.IsInSource
                  select x.SourceTree;

关于c# - 从 SymbolAnalysisContext 获取语法树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37695086/

相关文章:

roslyn - scriptcs 托管 - 优于 Roslyn

c# - 使用 Roslyn 更改语法标记

c# - 是否可以在 Visual Studio 中编译之前立即添加 C# 类

C#程序(进程)不会卸载

c# - 如何检查一个数字是否包含小数?

c# - LINQ 选择具有匿名类型的 Distinct

roslyn - 如何使用 Roslyn 获取 IEnumerable<T> 的基础类型?

c# - 在 Roslyn 中获取方法调用的基类

c# - 获取 "Could not find an implementation of the query pattern for source type ' ExcelQueryable<T >'. "错误

c# smtp发送问题?