c# - 如何获取 Roslyn 找不到的所有 C# 类型或命名空间?
问题描述
我正在使用 Roslyn 解析 C# 项目。我有一个Microsoft.CodeAnalysis.Compilation
代表这个项目的对象。但是,这个项目可能没有编译成功;这可能有几个原因,但我对任何对无法解析的类型或命名空间的引用特别感兴趣。如何使用我的Compilation
对象来检索所有未知的命名空间或类型作为IErrorTypeSymbol
s?
解决方案
最简单的方法是遍历所有SyntaxTree
s 并使用编译SemanticModel
来识别错误类型。
就像是...
// assumes `comp` is a Compilation
// visit all syntax trees in the compilation
foreach(var tree in comp.SyntaxTrees)
{
// get the semantic model for this tree
var model = comp.GetSemanticModel(tree);
// find everywhere in the AST that refers to a type
var root = tree.GetRoot();
var allTypeNames = root.DescendantNodesAndSelf().OfType<TypeSyntax>();
foreach(var typeName in allTypeNames)
{
// what does roslyn think the type _name_ actually refers to?
var effectiveType = model.GetTypeInfo(typeName);
if(effectiveType.Type != null && effectiveType.Type.TypeKind == TypeKind.Error)
{
// if it's an error type (ie. couldn't be resolved), cast and proceed
var errorType = (IErrorTypeSymbol)effectiveType.Type;
// do what you want here
}
}
}
未知名称空间在爬网后需要更多技巧,因为您无法真正判断Foo.Bar
是指“Foo 中的类型 Bar”还是没有元数据的“名称空间 Foo.Bar”。可能我忘记了 Roslyn 会走私类型引用语法节点的某个地方……但TypeName
我记得。
推荐阅读
- api - 微服务 HttpStatus 代码
- python - 如何向我的 Python 脚本添加循环函数和 1 分钟延迟?
- dart - 当我开始 web 颤振调试时的空白页面
- ssh - 有没有办法为 Visual Studio 2017 使用 SFTP 工具?
- angular - ***.service.ts(1,21) 中的错误:错误 TS2305:模块 '"***@angular/common/http"' 没有导出的成员 'Response'
- node.js - Next.js 的 NPM 包——它们需要在 ES5 中吗?
- c# - 为什么无法解析 Json 并显示原始结果?
- python - 如何在pyglet中制作一个带有面部图像的立方体
- jhipster - JHipster 升级继续使用以前的配置生成
- java - How can you automatically select a listcell when one of its internal components receives focus?