Getting the fully qualified name of a type from a TypeInfo object

前端 未结 3 955
再見小時候
再見小時候 2021-02-12 19:50

Is it somehow possible to get the fully qualified name of the type contained in a TypeInfo object?

In the debugger many of these values nicely show up as

3条回答
  •  伪装坚强ぢ
    2021-02-12 20:01

    Using the semantic model you can also do it like i did it here:

    var typeInfo = context.SemanticModel.GetTypeInfo(identifierNameSyntax);
    var namedType = typeInfo.Type as INamedTypeSymbol;
    if (namedType != null && namedType.Name == nameof(ConfiguredTaskAwaitable) && GetFullNamespace(namedType) == typeof(ConfiguredTaskAwaitable).Namespace)
        return true;
    

    where "GetFullNamespace" works like this:

        public static IEnumerable GetNamespaces(INamedTypeSymbol symbol)
        {
            var current = symbol.ContainingNamespace;
            while (current != null)
            {
                if (current.IsGlobalNamespace)
                    break;
                yield return current.Name;
                current = current.ContainingNamespace;
            }
        }
    
        public static string GetFullNamespace(INamedTypeSymbol symbol)
        {
            return string.Join(".", GetNamespaces(symbol).Reverse());
        }
    
        public static string GetFullTypeName(INamedTypeSymbol symbol)
        {
            return string.Join(".", GetNamespaces(symbol).Reverse().Concat(new []{ symbol.Name }));
        }
    

    Obviously Jason Malinowski's answer is more convenient for simple cases

提交回复
热议问题