Getting FullTypeName from ClassDeclarationSyntax

Proposed Getting FullTypeName from ClassDeclarationSyntax

  • 05 Desember 2011 11:22
     
      Memiliki Kode

    Hi

     

    Whats the best way to get the full typename when having a

    ClassDeclarationSyntax
    

    Instace ?

     

     

Semua Balasan

  • 05 Desember 2011 21:42
     
     Saran Jawaban Memiliki Kode

    Just ClassDeclarationSyntax isn't enough to get the full type name, you need semantic information for that. To get semantic information, you create a Compilation, then get a SemanticModel from it and then get Symbol for your class:

    string code = @"
    namespace N1
    {
        namespace N2
        {
            class C1<T1>
            {
                class C2<T2> { }
            }
        }
    }";
    
    var tree = SyntaxTree.ParseCompilationUnit(code);
    
    var c2 = tree.Root
        .DescendentNodes()
        .OfType<ClassDeclarationSyntax>()
        .Last();
    
    var compilation = Compilation.Create("compilation").AddSyntaxTrees(tree);
    
    var model = compilation.GetSemanticModel(tree);
    
    var symbol = model.GetDeclaredSymbol(c2);
    
    var fullName = symbol.ToString();
    

    After this, fullName is N1.N2.C1<T1>.C2<T2>. There is also an extension method ToDisplayString() which gives you more control about the exact format used.

    If you reference types from other assemblies, you have to add them to the compilation too.

  • 05 Desember 2011 21:44
     
     
    Fairly sure you have to build it yourself by walking up the nested types and name space building the string as you go. Why are you needing the full name?