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

前端 未结 1 1791
天命终不由人
天命终不由人 2021-01-14 07:56

When you hover over a \"simplified\" using directive in VS2015, it shows you the fully-qualified name. How would I get this information via a Roslyn plugin? Wou

1条回答
  •  情话喂你
    2021-01-14 08:52

    With the semantic model you can retrieve information about the semantics that make up your code (evidently) -- this allows you to get specific information about types and other constructs.

    For example:

    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())
        {
            var symbol = semanticModel.GetSymbolInfo(usingDirective.Name).Symbol;
            var name = symbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat);
            name.Dump();
        }
    }
    

    Output:

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

    If you use SymbolDisplayFormat.CSharpErrorMessageFormat instead, you will receive

    System.Text
    System
    System.IO

    Your choice what you're interested in but as you can see it works just fine with aliases and without.

    0 讨论(0)
提交回复
热议问题