简体   繁体   中英

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

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? Would it be using a DiagnosticAnalyzer ? A CodeFixProvider ?

Reading through source.roslyn.codeplex.com, there's tons of information there, including how to add a using statement , and also how to simplify type names (including using statements), but I'm unable to figure out how to go in reverse to get the fully-qualified name.

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<UsingDirectiveSyntax>())
    {
        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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM