如何从 Roslyn 中的 using 指令获取完全限定的命名空间?

How can I get the fully qualified namespace from a using directive in Roslyn?

当您将鼠标悬停在 VS2015 中的 "simplified" using 指令上时,它会显示完全限定名称。我如何通过 Roslyn 插件获取此信息?它会使用 DiagnosticAnalyzer 吗?一个CodeFixProvider?

通读 source.roslyn.codeplex.com,那里有大量信息,包括如何 add a using statement,以及如何简化类型名称(包括 using 语句),但我不能弄清楚如何反向获得完全限定名称。

使用语义模型,您可以检索有关构成代码的语义的信息(显然)——这使您可以获得有关类型和其他构造的特定信息。

例如:

void Main()
{
    var tree = CSharpSyntaxTree.ParseText(@"
using X = System.Text;
using Y = System;
using System.IO;

namespace ConsoleApplication1
{
}"
);

    var mscorlib = PortableExecutableReference.CreateFromFile(typeof(object).Assembly.Location);
    var compilation = CSharpCompilation.Create("MyCompilation", syntaxTrees: new[] { tree }, references: new[] { mscorlib });
    var semanticModel = compilation.GetSemanticModel(tree);
    var root = tree.GetRoot();

    // Get usings
    foreach (var usingDirective in root.DescendantNodes().OfType<UsingDirectiveSyntax>())
    {
        var symbol = semanticModel.GetSymbolInfo(usingDirective.Name).Symbol;
        var name = symbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat);
        name.Dump();
    }
}

输出:

global::System.Text
global::System
global::System.IO

如果您改用SymbolDisplayFormat.CSharpErrorMessageFormat,您将收到

System.Text
System
System.IO

您可以选择您感兴趣的内容,但如您所见,无论是否使用别名,它都可以正常工作。