Get fully-qualified metadata name in Roslyn

后端 未结 1 853
孤街浪徒
孤街浪徒 2020-12-09 17:08

I need to get the full CLR name of a particular symbol. This means that for generic types I need the `1, `2, etc. appended to types. Now, ISy

1条回答
  •  有刺的猬
    2020-12-09 17:35

    For now, having no better solution, I'm using the following:

    public static string GetFullMetadataName(this ISymbol s) 
    {
        if (s == null || IsRootNamespace(s))
        {
            return string.Empty;
        }
    
        var sb = new StringBuilder(s.MetadataName);
        var last = s;
    
        s = s.ContainingSymbol;
    
        while (!IsRootNamespace(s))
        {
            if (s is ITypeSymbol && last is ITypeSymbol)
            {
                sb.Insert(0, '+');
            }
            else
            {
                sb.Insert(0, '.');
            }
    
            sb.Insert(0, s.OriginalDefinition.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat));
            //sb.Insert(0, s.MetadataName);
            s = s.ContainingSymbol;
        }
    
        return sb.ToString();
    }
    
    private static bool IsRootNamespace(ISymbol symbol) 
    {
        INamespaceSymbol s = null;
        return ((s = symbol as INamespaceSymbol) != null) && s.IsGlobalNamespace;
    }
    

    which seems to work for now. Roslyn seems to have internal flags for SymbolDisplayFormat that enable that sort of thing (most notably SymbolDisplayCompilerInternalOptions.UseArityForGenericTypes, but not accessible to the outside.

    Above code could probably be faster on recent .NET versions by using Append instead of Insert on the StringBuilder, but that's something to leave for profiling.

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