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

笑着哭i 提交于 2019-12-19 10:09:08

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/36407563/how-can-i-get-the-fully-qualified-namespace-from-a-using-directive-in-roslyn

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!