Get the type name

后端 未结 10 864
星月不相逢
星月不相逢 2020-12-05 23:05

How i can get full right name of generic type?

For example: This code

typeof(List).Name

return

10条回答
  •  长情又很酷
    2020-12-05 23:28

    Came across this and thought I'd share my own solution. It handles multiple generic arguments, nullables, jagged arrays, multidimensional arrays, combinations of jagged/multidimensional arrays, and any nesting combinations of any of the above. I use it mainly for logging so that it's easier to identify complicated types.

    public static string GetGoodName(this Type type)
    {
        var sb = new StringBuilder();
    
        void VisitType(Type inType)
        {
            if (inType.IsArray)
            {
                var rankDeclarations = new Queue();
                Type elType = inType;
    
                do
                {
                    rankDeclarations.Enqueue($"[{new string(',', elType.GetArrayRank() - 1)}]");
                    elType = elType.GetElementType();
                } while (elType.IsArray);
    
                VisitType(elType);
    
                while (rankDeclarations.Count > 0)
                {
                    sb.Append(rankDeclarations.Dequeue());
                }
            }
            else
            {
                if (inType.IsGenericType)
                {
                    var isNullable = inType.IsNullable();
                    var genargs = inType.GetGenericArguments().AsEnumerable();
                    var numer = genargs.GetEnumerator();
    
                    numer.MoveNext();
    
                    if (!isNullable) sb.Append($"{inType.Name.Substring(0, inType.Name.IndexOf('`'))}<");
    
                    VisitType(numer.Current);
    
                    while (numer.MoveNext())
                    {
                        sb.Append(",");
                        VisitType(numer.Current);
                    }
    
                    if (isNullable)
                    {
                        sb.Append("?");
                    }
                    else
                    {
                        sb.Append(">");
                    }
                }
                else
                {
                    sb.Append(inType.Name);
                }
            }
        }
    
        VisitType(type);
    
        var s = sb.ToString();
    
        return s;
    }
    

    This:

    typeof(Dictionary>>).GetGoodName()
    

    ...returns this:

    Dictionary>>
    

提交回复
热议问题