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

自闭症网瘾萝莉.ら 提交于 2019-12-01 10:43:39

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.

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