我正在使用Roslyn解析C#项目。我有一个代表该项目的Microsoft.CodeAnalysis.Compilation
对象。但是,该项目可能尚未成功编译。可能有多种原因,但是我对无法解决的对类型或名称空间的任何引用特别感兴趣。 如何使用我的Compilation
对象以IErrorTypeSymbol
的形式检索所有未知的名称空间或类型?
答案 0 :(得分:1)
最简单的方法是遍历所有SyntaxTree
并使用编译的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的名称空间Foo.Bar”。可能我忘记了罗斯林会走私类型引用语法节点的地方...但是我记得TypeName
。