如何获取Roslyn找不到的所有C#类型或名称空间?

时间:2020-07-06 20:23:54

标签: c# roslyn code-analysis roslyn-code-analysis

我正在使用Roslyn解析C#项目。我有一个代表该项目的Microsoft.CodeAnalysis.Compilation对象。但是,该项目可能尚未成功编译。可能有多种原因,但是我对无法解决的对类型或名称空间的任何引用特别感兴趣。 如何使用我的Compilation对象以IErrorTypeSymbol的形式检索所有未知的名称空间或类型?

1 个答案:

答案 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