首页 > 解决方案 > 如何获取 Roslyn 找不到的所有 C# 类型或命名空间?

问题描述

我正在使用 Roslyn 解析 C# 项目。我有一个Microsoft.CodeAnalysis.Compilation代表这个项目的对象。但是,这个项目可能没有编译成功;这可能有几个原因,但我对任何对无法解析的类型或命名空间的引用特别感兴趣。如何使用我的Compilation对象来检索所有未知的命名空间或类型作为IErrorTypeSymbols?

标签: c#roslyncode-analysisroslyn-code-analysis

解决方案


最简单的方法是遍历所有SyntaxTrees 并使用编译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我记得。


推荐阅读